Making structure arrays programmtically.
Ältere Kommentare anzeigen
Hello Guys,
I have been trying to do the following programmatically and I have not been successful so far (excuse my ignorance if this is a trivial problem for most of you).
I have the following data:
Day of Month Temperature Pressure Day1 15 101.3 Day2 25 98
I want a structure, for example, mystruct to look like below.
mystruct.Dayofmonth = {'Day1'; 'Day2'} mystruct.Temperature = [15 ; 25]; mystruct.Pressure = [101.3; 98];
My aim is to group all the temperatures under 'temperature' field and pressures under 'pressure' (and similarly the day of the month field also). I would like to do this programatically so that I can use this concept for creating such structures dynamically(i.e., without having to hard code the name of the fields).
This is my first post under mathworks answers. I have been a great fan of the products and of the openmindedness to share ideas in this group.
Thanks. -Mahesh
5 Kommentare
Mahesh
am 2 Jul. 2011
Oleg Komarov
am 2 Jul. 2011
How do you retrieve the source data. Is it always on one line?
Mahesh
am 4 Jul. 2011
Oleg Komarov
am 4 Jul. 2011
DO you have it on .txt with headers?
Mahesh
am 5 Jul. 2011
Akzeptierte Antwort
Weitere Antworten (2)
Robert Cumming
am 5 Jul. 2011
you can make fields in a structure dynamically, i.e.
yourStruct.(yourVariable) = value
The fields in your structure can be accessed incrementally i.e.
yourStruct.(yourVariable)(index)
etc....
Fangjun Jiang
am 5 Jul. 2011
Yes, the structure array would be perfect for your need. Based on your sample data, you can do.
Dayofmonth = {'Day1'; 'Day2'};
Temperature = [15 ; 25];
Pressure = [101.3; 98];
Temperature=mat2cell(Temperature,ones(size(Temperature)),1);
Pressure=mat2cell(Pressure,ones(size(Pressure)),1);
mystruct=struct('Dayofmonth',Dayofmonth,'Temperature',Temperature,'Pressure',Pressure)
mystruct(1)
mystruct(2)
[mystruct.Temperature]
mystruct =
2x1 struct array with fields:
Dayofmonth
Temperature
Pressure
ans =
Dayofmonth: 'Day1'
Temperature: 15
Pressure: 101.3000
ans =
Dayofmonth: 'Day2'
Temperature: 25
Pressure: 98
3 Kommentare
Mahesh
am 5 Jul. 2011
Fangjun Jiang
am 5 Jul. 2011
To have meaningful field names like Temperature and Pressure, you have to specify it manually one way or another. You could generate field names programmatically, such as,
a=struct('FirstField',1);
for k=2:3
FieldName=['Field',num2str(k)];
a=setfield(a,FieldName,k);
end
BTW, I modified my original code to use function ones(), instead of repmat().
Fangjun Jiang
am 5 Jul. 2011
If you mean dynamic field name, you could also do.
a=struct('FirstField',1);
for k=2:3
FieldName=['Field',num2str(k)];
a.(FieldName)=k;
end
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!