Generating structure name from a variable

1 view (last 30 days)
Hello, I have a code that is calculating a bunch of data related to something in a series of somethings. e.g. baseball1...baseball2.... The scripts call for the only input I need is to type 1 or 2 or whatever number I'm looking for. I want to be able to make a structure named baseball1 that I can then save all my data to specific fields. However I cannot type sprintf(baseball%d,'baseballnumber') = struct(); because then it yields 'sprintf' as the name of the structure. It is important to be named that since it will be saved with the series of structures in same folder.

Accepted Answer

per isakson
per isakson on 16 Jan 2014
Edited: per isakson on 16 Jan 2014
No, you cannot. However, if all the baseballs have the same set of fields you might try something like:
>> baseball.Name = 'a'
baseball =
Name: 'a'
>> baseball(2).Name = 'b'
baseball =
1x2 struct array with fields:
Name
>> baseball(3).Name = 'c'
baseball =
1x3 struct array with fields:
Name
>> {baseball.Name}
ans =
'a' 'b' 'c'
  2 Comments
Bernard
Bernard on 16 Jan 2014
Thanks man, that was my back up plan I guess I'll revert to it.
per isakson
per isakson on 16 Jan 2014
Edited: per isakson on 16 Jan 2014
Seriously, I think your back up plan is much better. Why do you prefer "baseball1", etc. ?
Old trick that I had forgotten. It doesn't work with a static workspace:
>> for k = 1:11, assign( sprintf( 'var%d', k ), k ), end
>> assign( sprintf('baseball%d', baseballnumber ), struct() )
where
function assign( Name, Value )
assignin( 'caller', Name, Value );
end
Read this:

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!