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!