Produce a new matrix,Z from X and Y matrices

5 views (last 30 days)
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’

Accepted Answer

Star Strider
Star Strider on 8 Aug 2019
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 Comments
Star Strider
Star Strider on 8 Aug 2019
As always, my pleasure!
This was an interesting problem!
JL
JL on 8 Aug 2019
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

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!