I have an array like this:
s.x
ans = 4000
280
ans = 4272.5
282
ans = 4553.85
284.29
etc......
I would like to access the first element in each case to plot their values (4000 4272.5 4553.85).
s(1,1).x([1]) yields 4000
s(1,2).x([1]) yields 4272.5
s(1, 1:2).x([1]) gives error: a cs-list cannot be further indexed.
What is the proper syntax needed to yield an array containing the values 4000 4272.5 and 4553.85 please?

답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 12월 2일
편집: Ameer Hamza 2020년 12월 2일

1 개 추천

You can use arrayfun()
v = arrayfun(@(s_) s_.x(1), s)
Indexing of struct arrays and cell arrays can be a bit confusing in MATLAB. Check the following links
Following is another solution
v = [s.x];
v = v(1,:);

댓글 수: 4

Chris Stillo
Chris Stillo 2020년 12월 2일
Thanks,
arrayfun works for me, although I think I'll just use it for now and try to understand it later!
I am glad to be of help! :)
In short, arrayfun is just a for-loop. Following two codes are same
v = arrayfun(@(s_) s_.x(1), s)
or
v = zeros(size(s));
for i = 1:numel(v)
v(i) = s(i).x(1);
end
Chris Stillo
Chris Stillo 2020년 12월 2일
That's great. Thanks again.
Ameer Hamza
Ameer Hamza 2020년 12월 2일
I am glad to be of help!

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

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

질문:

2020년 12월 2일

댓글:

2020년 12월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by