resize a matrix and missed data "zero"

1 次查看(过去 30 天)
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?

采纳的回答

Voss
Voss 2022-4-9
% first matrix:
A = [1 2 5; 80 50 60];
% these two lines of code work for a single matrix:
new_A = [1:5; zeros(1,5)];
new_A(2,A(1,:)) = A(2,:)
new_A = 2×5
1 2 3 4 5 80 50 0 0 60
% second matrix:
A = [1 3 4; 40 65 23];
% same two lines of code as above:
new_A = [1:5; zeros(1,5)];
new_A(2,A(1,:)) = A(2,:)
new_A = 2×5
1 2 3 4 5 40 0 65 23 0
% alternatively, a cell array of all your matrices:
A = {[1 2 5; 80 50 60]; [1 3 4; 40 65 23]};
% put those two lines of code in a function and
% use cellfun to apply it to all the matrices:
new_A = cellfun(@expand_matrix,A,'UniformOutput',false)
new_A = 2×1 cell array
{2×5 double} {2×5 double}
new_A{:}
ans = 2×5
1 2 3 4 5 80 50 0 0 60
ans = 2×5
1 2 3 4 5 40 0 65 23 0
function new_A = expand_matrix(A)
new_A = [1:5; zeros(1,5)];
new_A(2,A(1,:)) = A(2,:);
end

更多回答(2 个)

the cyclist
the cyclist 2022-4-9
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
Mexpanded = 2×5
1 2 3 4 5 80 50 0 0 60
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.

MJFcoNaN
MJFcoNaN 2022-4-9
编辑:MJFcoNaN 2022-4-9
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_1 = 2×5
1 2 3 4 5 80 50 0 0 60
new_2=[x;y(2,:)]
new_2 = 2×5
1 2 3 4 5 40 0 65 23 0

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by