sum of a vector with non zero elements of matrix without using loop

2 views (last 30 days)
I have a matrix T and vector M say
T=[0 0 1 0 0 0 1 0 0 0
0 1 0 0 0 1 0 0 1 1
0 1 0 0 0 0 0 0 1 1
0 0 1 0 1 0 1 1 1 0
0 0 1 1 1 1 0 1 1 0]
M=[0.1 0.2 0.2 0.4 0.2 0.3 0.1 0.1 0.1 0.2]
I want to add M in each row of T with only non zero element. For example, the result of 1st row should be
0 0 1.2 0 0 0 1.1 0 0 0
but is this possible without applying for loop?
  3 Comments
Image Analyst
Image Analyst on 28 Aug 2018
How are you getting 1.1 and 1.2? what values are being summed to give those numbers? You say for "each row of T with only non zero element." Well, that would be every single row of T because every single row of T has non-zero elements. And M sums to 1.9, so wouldn't every element of the output matrix be 1.9? And give any remaining rows of the output - why did you give only the first row???
Even if M took on the values of T where the elements of T were not zero, that would give output(1,:)=[0 0 0.2 0 0 0 0.1 0, 0, 0] because the 3rd and 7th element of T in that row are non-zero. I have no idea what you want.

Sign in to comment.

Accepted Answer

Pierre845
Pierre845 on 28 Aug 2018
You can do:
R = repmat(M, 5, 1);
Q = (T+R).*T;

More Answers (0)

Community Treasure Hunt

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

Start Hunting!