resize a matrix and missed data "zero"
Show older comments
Hi! I have a data which are is like:
[1 2 5; 80 50 60], [1 3 4; 40 65 23], ...and i want to change all of them to [1 2 3 4 5;80 50 0 0 60], [1 2 3 4 5; 40 0 65 23 0] without loop. It means first row for all shuld be numbers 1-5 and the second row the related number and for not existing data a zero. how is it possible?
Accepted Answer
More Answers (2)
Here is one way:
M = [ 1 2 5;
80 50 60];
Mrange = M(1,1):M(1,end);
Mexpanded = [Mrange; zeros(1,M(1,end))];
Mexpanded(:,M(1,:)) = M
It might make some assumptions based on the two example you gave (which both started with 1, and are sorted, for example). You might need to generalize, if you have cases that look different.
I answered a very similar question recently, what a coincidence:
array_1=[1 2 5; 80 50 60];
array_2=[1 3 4; 40 65 23];
% same code
x1 = array_1(1, :);
y1 = array_1(2, :);
x2 = array_2(1, :);
y2 = array_2(2, :);
x = unique([x1, x2]);
y = zeros(2, length(x));
[~, locb1] = ismember(x1, x);
[~, locb2] = ismember(x2, x);
y(1, locb1) = y1;
y(2, locb2) = y2;
% additional step for your task
new_1=[x;y(1,:)]
new_2=[x;y(2,:)]
Categories
Find more on Logical 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!