resize a matrix and missed data "zero"
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
sia ben
el 9 de Abr. de 2022
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 comentarios
Respuesta aceptada
Voss
el 9 de Abr. de 2022
% 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 comentarios
Más respuestas (2)
the cyclist
el 9 de Abr. de 2022
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 comentarios
MJFcoNaN
el 9 de Abr. de 2022
Editada: MJFcoNaN
el 9 de Abr. de 2022
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 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!