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

2 views (last 30 days)
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?

Accepted Answer

Matt J
Matt J on 2 Aug 2020
Edited: Matt J on 2 Aug 2020
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

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!