acces data in struct

조회 수: 1 (최근 30일)
Rica
Rica 2019년 7월 19일
댓글: Mario Chiappelli 2019년 7월 19일
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!

채택된 답변

Peter Jarosi
Peter Jarosi 2019년 7월 19일
편집: Peter Jarosi 2019년 7월 19일
You can use for loop indexing elements of your structure:
myElements = fieldnames(Str);
% or you can list your elements
% myElements = {'A', 'B', 'C'};
for x = 1 : length(myElements)
e1 = myElements{x};
e2 = strcat(e1, '1');
Str.(e1)=Str.(e2)(500:1500);
end
Please, let me know if it works for you
  댓글 수: 2
Rica
Rica 2019년 7월 19일
it works! but you should change this:
e2 = strcat(e1);
Thank you!
Peter Jarosi
Peter Jarosi 2019년 7월 19일
편집: Peter Jarosi 2019년 7월 19일
You're very welcome!
You are right, if you want to overwrite your existing instances. In this case strcat() is even unnecessary:
myElements = fieldnames(Str);
% or you can list your elements
% myElements = {'A', 'B', 'C'};
for x = 1 : length(myElements)
e1 = myElements{x};
Str.(e1)=Str.(e1)(500:1500);
end
but in your question you wrote:
Str.A1=Str.A(500:1500);
that's why I thought that you want to create new elements of your structure in order to save old ones.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Mario Chiappelli
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
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
Mario Chiappelli 2019년 7월 19일
*thumbs up emoji

댓글을 달려면 로그인하십시오.


Rica
Rica 2019년 7월 19일
Thank you to every one!

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by