acces data in struct
이전 댓글 표시
Hi!
I have a struct Str. the element of the structure arle A, B, C,.... all of the are arrays with length 2000. I want to have onle the element from 500:1500 without writing
Str.A1=Str.A(500:1500) for every struct element.
is there an easy way to achieve this goal?
thank you!
채택된 답변
추가 답변 (2개)
Mario Chiappelli
2019년 7월 19일
편집: Mario Chiappelli
2019년 7월 19일
I would loop through each A,B,C... Other languages call this a for each loop.
for str = {'A','B','C'}
variableName = strcat(str{1},'1');
Str.(variableName) = Str.(str{1})(500:1500);
end
Note: Instead of looping through numbers where each iteration is stored in the for statement variable "i" (or whatever you decide to call it), you are looping through each letter and the for statement variable in this case is "str".
댓글 수: 6
Peter Jarosi
2019년 7월 19일
편집: Peter Jarosi
2019년 7월 19일
I think your code won't work, because, for instance you should use Str.(variableName) syntax instead of Str.variableName (and other problems).
Mario Chiappelli
2019년 7월 19일
What are these "other problems", you did exactly what I did but you put the parantheses around the variables.
Peter Jarosi
2019년 7월 19일
편집: Peter Jarosi
2019년 7월 19일
I didn't see your code when I was writing mine. You were just faster than me in order to submit it, and less accurate, and still having syntax errors. Test it first, before submit!
Peter Jarosi
2019년 7월 19일
It's a nice trick:
for str = {'A','B','C'}
but in this case doesn't work properly, because you will get 1x1 cells instead of strings. So you need one more step in order to convert them to strings, otherwise you won't be able to use them inside the parenthesis syntax.
Peter Jarosi
2019년 7월 19일
Good job! I've given you a vote for it.
One little thing is left. Change "1" to '1'
Mario Chiappelli
2019년 7월 19일
*thumbs up emoji
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!