How to access and use specific data from a structure
4 次查看(过去 30 天)
显示 更早的评论
Hello there!
So have a structure 1x1 with 10 (8760x1) elements. I want to create a script to access to each of these 10 groups of data and I want to evaluate different functions and in order to get a vector with the result of the evaluated function.
For example, I want to access the data to get the maximum value at each time, so I want to get a vector with ten elements showing me the maximum value of each group of data.
So "Graph" is the name of the structure, and "Curve'n' " is each of the 10 arrays that I need to evaluate. I have used this and it works but I find it not very practical because I have to write the whole expression down
m(i)=max(Graph.Curve1);
m(i+1)=max(Graph.Curve2);
m (i+2)=max(Graph.Curve3);
m (i+3)=max(Graph.Curve4); ...... and so on till 10
I have tried
for i=1:10;
m(i)=max(Graph.Curve"i");
end
m
But it doesn't work.
Is there a more practical way to do this?
Thank you very much.
Best regards.
1 个评论
Walter Roberson
2012-6-25
http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
采纳的回答
更多回答(3 个)
grapevine
2012-6-25
Try to use this function : eval Use my code as example
Graph.Curve1=[1 2]
max(eval(['Graph.Curve',num2str(1)]))
good luck
3 个评论
grapevine
2012-6-26
i don't get it
why not?
Using eval hurts someone, doesn't it?
http://www.mathworks.fr/matlabcentral/answers/?search_submit=answers&query=eval+problem&term=eval+problem
Jan
2012-6-25
Graph.Curve1 = [1 2];
max(Graph.(sprintf('Curve%d', 1)))
This method is called "dynamic fieldnames". In opposite to the evil eval it is safe, fast, easy to debug and let Matlab to process the code efficiently.
It is a good programming practice not to include indices in the names of variables. Obviously indices are a good method to implement indices, e.g.: Graph.Curve{1}, Graph.Curve{2}, ...
2 个评论
Image Analyst
2012-6-25
Artu you can do it this way, but which way do you think is easier for someone else to understand when it comes time for them to take over your code, or when you look at it a year from now, dynamic field names, or the way you did it at first? If you gave Tom's, andrei's, Jan's, and your code to your classmate, which would he understand? Not to say that dynamic field names don't have their place, but come on, it's only 10 lines of code - not that many. If you had hundreds of them then that might be a different matter. Not to take anything away from Jan's clever solution, but personally I'd vote in favor of the way you originally did it as being the way that is easier to understand. For me, I always keep in mind maintainability and not just compactness when writing code. I'm probably in the minority but that's just my 2 cents...
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!