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?
0 个评论
采纳的回答
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,:)
% 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,:)
% 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{:}
function new_A = expand_matrix(A)
new_A = [1:5; zeros(1,5)];
new_A(2,A(1,:)) = A(2,:);
end
0 个评论
更多回答(2 个)
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
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.
0 个评论
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_2=[x;y(2,:)]
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!