How to subsequently adding the matrix from row to row.
1 view (last 30 days)
Show older comments
I have a matrix
x = [360 672 467 0 0 0 0 0 0 0
892 963 0 400 0 0 0 0 0 0
738 696 0 504 517 0 0 0 0 0
10 0 20 0 20 840 0 0 0 0]
and another matrix
y = [0 0 1 2
0 0 0 0
0 0 0 4
3 0 5 6];
The coding that I wrote has some problem when it meet the first row which start at 0. The following is my code.
%Initialization.
a = 1;
z = zeros();
for t = 1 : size(y, 1)
for b = 1 : size(y, 2)
if y(a, b) ~= 0
z(b) = x(t, y(a, b));
p = 1;
for q = 1 : size(y, 1)
if q == 1
if y(a, b) ~= 0
z(b) = x(t, y(a, b));
p = p - 1;
end
elseif y(a + p, b) ~= 0
z(b) = z(b) + x(t, y(a + p, b));
end
p = p + 1;
end
end
end
z
end
How do I get the result such as
467 0 360 672
0 0 892 1363
0 0 1255 1200
20 0 30 840
what do i missing?
Thank you.
0 Comments
Accepted Answer
Andrei Bobrov
on 15 Dec 2011
m = size(y,2);
out = zeros(size(x,1),m)
for j1 = 1:m
out(:,j1) = sum(x(:,nonzeros(y(:,j1))),2);
end
More Answers (1)
the cyclist
on 15 Dec 2011
x = [360 672 467 0 0 0 0 0 0 0
892 963 0 400 0 0 0 0 0 0
738 696 0 504 517 0 0 0 0 0
10 0 20 0 20 840 0 0 0 0];
y = [0 0 1 2
0 0 0 0
0 0 0 4
3 0 5 6];
z = zeros(size(x,1),size(y,2));
for j = 1:size(y,2)
ycol = y(:,j);
idx = ycol(ycol>0);
z(:,j) = sum(x(:,idx),2);
end
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!