Azzera filtri
Azzera filtri

Generating structure name from a variable

3 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

per isakson
per isakson il 16 Gen 2014
Modificato: per isakson il 16 Gen 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 Commenti
Bernard
Bernard il 16 Gen 2014
Thanks man, that was my back up plan I guess I'll revert to it.
per isakson
per isakson il 16 Gen 2014
Modificato: per isakson il 16 Gen 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:

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by