필터 지우기
필터 지우기

Produce a new matrix,Z from X and Y matrices

조회 수: 1 (최근 30일)
JL
JL 2019년 8월 8일
댓글: JL 2019년 8월 8일
I have 2 matrices, and I would like to derive another matrix, Z from X and Y. So for each row starting and ending the same, sum of their corresponding values in X. For example, in Y, any row starting and ending with 1 and 2 respectively, loop up at their X values, and sum them up i.e. 25+1+3=29. Then perform the same method for the rest.
X = [25;
1;
3;
28;
6;
7;
25;
6;
9;
25;
10;
11;
15;
14;
12;
13;
25;
14;
15;]
Y = [1 2 0 0;
1 3 2 0;
1 4 3 2;
1 3 0 0;
1 2 3 0;
1 4 3 0;
1 4 0 0;
1 3 4 0;
1 2 3 4;
2 3 0 0;
2 1 3 0;
2 1 4 3;
2 1 4 0;
2 3 4 0;
2 1 3 4;
2 3 1 4;
3 4 0 0;
3 1 4 0;
3 2 1 4;]
Z = [25+1+3; % start ‘1’ and end with ‘2’
28+6+7; % start ‘1’ and end with ‘3’
25+6+9; % start ‘1’ and end with ‘4’
25+10+11; % start ‘2’ and end with ‘3’
15+14+12+13; % start ‘2’ and end with ‘4’
25+14+15;] % start ‘3’ and end with ‘4’

채택된 답변

Star Strider
Star Strider 2019년 8월 8일
One option:
for k = 1:size(Y,1)
[~,Zc] = find(Y(k,:) ~= 0, 1, 'last'); % Last Non-Zero Column
Z2(k,:) = Y(k,Zc); % Element Of Last Non-Zero Column
end
Z = accumarray([Z2 Y(:,1)], X)
producing:
Z =
0 0 0
29 0 0
41 46 0
40 54 54
To print it out:
[Zs,Ze] = meshgrid(1:3, 1:4);
Zsc = Zs(:);
Zec = Ze(:);
fprintf(1, 'Starts with %d, Ends with %d, Z = %2d\n', [Zs(:), Ze(:), Z(:)]')
producing:
Starts with 1, Ends with 1, Z = 0
Starts with 1, Ends with 2, Z = 29
Starts with 1, Ends with 3, Z = 41
Starts with 1, Ends with 4, Z = 40
Starts with 2, Ends with 1, Z = 0
Starts with 2, Ends with 2, Z = 0
Starts with 2, Ends with 3, Z = 46
Starts with 2, Ends with 4, Z = 54
Starts with 3, Ends with 1, Z = 0
Starts with 3, Ends with 2, Z = 0
Starts with 3, Ends with 3, Z = 0
Starts with 3, Ends with 4, Z = 54
Experiment to get the result you want.
  댓글 수: 5
Star Strider
Star Strider 2019년 8월 8일
As always, my pleasure!
This was an interesting problem!
JL
JL 2019년 8월 8일
Star Strider, I have another intetesting problem, was wondering if you are interested to take a look - here is the link to the question https://uk.mathworks.com/matlabcentral/answers/475460-sharing-values-of-elements-in-a-matrix

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by