How to set value in a matrix

I have a double matrix 4x5 matrix
A=[11 12 13 14 15;
21 22 23 24 25;
31 32 33 34 35;
41 42 43 44 45],
B=[3 0 2 4 1]
B indicates to set all the rows of B[i] in A(from row 1 to that position) to 0.
C = [0 12 0 0 0;
0 22 0 0 25;
0 32 33 0 35;
41 42 43 0 45]
Thanks

 Accepted Answer

for i = 1:numel(B)
A(1:B(i),i) = 0;
end

4 Comments

Simple and effective. I tried to see which of the two is faster, but timeit warns me it is running too fast for an accurate measurement.
clc
timeit(@fun1)
timeit(@fun2)
timeit(@fun2_compact)
function A=fun1
A=[11 12 13 14 15;
21 22 23 24 25;
31 32 33 34 35;
41 42 43 44 45];
B=[3 0 2 4 1];
for i = 1:numel(B)
A(1:B(i),i) = 0;
end
end
function A=fun2
A=[11 12 13 14 15;
21 22 23 24 25;
31 32 33 34 35;
41 42 43 44 45];
B=[3 0 2 4 1];
a=-(1:size(A,1))';
L= a+B(:)' >=0;
A(L)=0;
end
function A=fun2_compact
A=[11 12 13 14 15;
21 22 23 24 25;
31 32 33 34 35;
41 42 43 44 45];
B=[3 0 2 4 1];
A(-(1:size(A,1))'+B(:)'>=0)=0;
end
Shannon
Shannon on 5 Feb 2020
Edited: Rik on 5 Feb 2020
Thank you so much, Rik! It is awesome!
You're welcome
Thanks for the timing comparisons, Rik!
One way around the limitations to timeit is by increasing the size of the arrays. With the large array inputs below, both of your solutions are faster.
A = randi(10000,1000);
B=randi(10000,1,1000)-1;
ans =
0.18254 % fun1 (my loop)
ans =
0.026578 % fun2
ans =
0.026723 % funct_compact

Sign in to comment.

More Answers (1)

This was a fun puzzle. I believe the code below is one of the many possible solutions. It does use implicit expansion, so for pre-R2016b you will have to use bsxfun.
A=[11 12 13 14 15;
21 22 23 24 25;
31 32 33 34 35;
41 42 43 44 45];
B=[3 0 2 4 1];
a=-(1:size(A,1))';
L= a+B(:)' >=0; %the (:)' is to ensure B is a row vector
C=A;C(L)=0

3 Comments

+1; although I like your compact version even better.
Thank you. While I like the one-linerness of the compact version, I think it looks like voodoo witchcraft, so I decided to post this as the answer
Ha! I know what you mean....

Sign in to comment.

Categories

Asked:

on 5 Feb 2020

Commented:

on 6 Feb 2020

Community Treasure Hunt

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

Start Hunting!