How to subsequently adding the matrix from row to row.
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Andrei Bobrov
2011-12-15
m = size(y,2);
out = zeros(size(x,1),m)
for j1 = 1:m
out(:,j1) = sum(x(:,nonzeros(y(:,j1))),2);
end
更多回答(1 个)
the cyclist
2011-12-15
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!