find the index who have the max value in cell structure

조회 수: 3 (최근 30일)
ahmad
ahmad 2022년 8월 23일
댓글: Voss 2022년 8월 30일
i have a cell structure like this:
ex1=[1 2 3];
ex2=[2 3 0];
for i=1:3
a(i).b=struct('ex1',ex1(i),'ex2',ex2(i));
end
how can i find the index of a(i) who have the max value of ex1 but the ex2 must be greater than 0?

채택된 답변

Voss
Voss 2022년 8월 23일
편집: Voss 2022년 8월 30일
ex1=[1 2 3];
ex2=[0 3 2];
for i=1:3
a(i).b = struct('ex1',ex1(i),'ex2',ex2(i));
end
temp = [a.b];
posidx = find([temp.ex2] > 0);
[maxval,tempidx] = max([temp(posidx).ex1]);
maxidx = posidx(tempidx);
disp(maxval);
3
disp(maxidx);
3
  댓글 수: 2
ahmad
ahmad 2022년 8월 30일
why if the ex2 start with 0 the answer of index is not the same as the max value of ex1 anymore?
for example is i change ex2 to ex2=[0 3 2] like this
ex1=[1 2 3];
ex2=[0 3 2];
for i=1:3
a(i).b = struct('ex1',ex1(i),'ex2',ex2(i));
end
temp = [a.b];
[maxval,maxidx] = max([temp([temp.ex2] > 0).ex1])
maxval = 3
maxidx = 2
the answer is maxval=3 and maxidx=2?
isn't the answer suppost to be maxval=3 and maxidx=3?
Voss
Voss 2022년 8월 30일
You're right. I've changed the answer and changed the ex2 to [0 3 2], and it now gives the expected result.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by