How to logically index multiple indices while indexing other indices normally?

조회 수: 4 (최근 30일)
I have a piece of code like so:
cond = ~(El.brute(:,:, iTraj) >= El_tmp);
for k = 1:d_unc
jS.brute(k, cond, iTraj) = j(k)+1;
end
where k and iTraj are integers (stored as doubles in typical Matlab fashion), and cond is a 10 by 3 logical matrix. jS.brute is 5 by 3 by 10 by 250.
The assignment in the 3rd line doesn't do what I expected. If I evaluate
jS.brute(k, :, :, iTraj)
It does not evaluate to j(k)+1 for the places where cond is true. Also, this assignment makes the 2nd size of jS.brute have 30 length.
It seems that Matlab will linearize any logical matrix you give for logical indexing, and it will apply only to one index.
My question is: what is the "best" way to do what I want to do here?
Do I have to use re-shape or is there a better way?
I guess I could permute so that the logical indexes are at the end. Is that better?

채택된 답변

Matt J
Matt J 2020년 8월 2일
편집: Matt J 2020년 8월 2일
You probably won't notice much difference with such small data sizes, but reshape is slightly better than permute because it will avoid additional memory allocation,
jS.brute=reshape(jS.brute,5,30,250);
cond = ~(El.brute(:,:, iTraj) >= El_tmp); %shouldn't this be tranposed to 3x10??
for k = 1:d_unc
jS.brute(k, cond, iTraj) = j(k)+1;
end

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by