MATLAB Answers

How to efficiently match the zeros of 1 matrix with another

18 views (last 30 days)
Pablo Aravena
Pablo Aravena on 27 Oct 2020 at 17:18
Edited: KSSV on 27 Oct 2020 at 17:41
Hello, I am solving an inverse problem through simulated annealing, but the loop I use to match the zeros of my data with zeros in my model (so that the inversion is only solved for non-zero elements of data) is making my code very inefficient.
D is the data matrix of dimensions 26x12x160 with many zeros
S is my model, it has the same dimensions, I want it to have zeros where D has zeros
I am using the following loop for this
for i=1:length(D(:,1,1))
for j=1:length(D(1,:,1))
for k=1:length(D(1,1,:))
if D(i,j,k)==0
S(i,j,k)=0;
end
end
end
end
Is there a more efficient way to do this? Maybe a way to kill 1 loop? I am very inexperienced with efficient coding...
Thanks in advance

  0 Comments

Sign in to comment.

Accepted Answer

KSSV
KSSV on 27 Oct 2020 at 17:23
Edited: KSSV on 27 Oct 2020 at 17:41
If D and S are your matrices of size 26*12*160. To repalce zeros in S where D is zero, simply use:
idx = D ==0 ; % get indices in A where it has values 0
S(idx) = 0 ; % repalce the indices with 0

  0 Comments

Sign in to comment.

More Answers (1)

Bruno Luong
Bruno Luong on 27 Oct 2020 at 17:37
Edited: Bruno Luong on 27 Oct 2020 at 17:39
The 3 for-loops can be shrink down to
S(D==0) = 0;

  0 Comments

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!