resize a matrix and missed data "zero"
    조회 수: 2 (최근 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에서 Logical에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



