Replacing specific values in each matrix row in all values in the matrix

조회 수: 1 (최근 30일)
I have a matrix as follows A=[8 66 92 101 0; 14 52 80 76 0; 16 66 33 51 7]. I want to read the rows column by column and assign all values in the matrix the first value of the row, my code so far works (I have also made an if loop to ignore the zeros), and the output is B=[8 8 8 8 0; 14 14 14 14 0; 16 16 16 16 16], however this isn't exactly what I need. For example, the matrix I need is B=[8 8 8 8 0: 14 14 14 14 0; 8 8 8 8 8] since A(1,2)=66 and this should have already been assigned to the value 8. So what I am looking for is to iterate over each row and column, assign all numbers in the row to the same value throughout the matrix, and whenever the value appears in a row later on the whole row again be assigned to the value, 8, in this example. I hope that this is clear enough. So far, the code is:
F=Locations;
indices = find(F(:,1)==0);
F(indices,:) = [];
for l=1:size(F,1);
for k=1:size(F,2);
if F(l,k)~=0;
[R,L]=find(F==F(l,k));
F(R,L)=F(l,1);
end
end
end

채택된 답변

Stephen23
Stephen23 2016년 2월 1일
편집: Stephen23 2016년 2월 1일
Try this:
A = [8 66 92 101 0; 14 52 80 76 0; 16 66 33 51 7; 1 76 66 0 0]
% get unique elements, row-wise:
[~,X,Y] = unique(A.','first');
% indices where elements first appear:
S = size(A.');
[C,R] = ind2sub(S,X(Y));
R = reshape(R,S)
% for each row find "first" appearance:
R(0==A.') = Inf;
D = A(min(R,[],1));
% create output array using "first" values:
out = bsxfun(@times,D(:),cumprod(+(A>0),2))
creates this:
out =
8 8 8 8 0
14 14 14 14 0
8 8 8 8 8
8 8 8 0 0
  댓글 수: 4
Stephen23
Stephen23 2016년 2월 1일
편집: Stephen23 2016년 2월 1일
Please see my edited question.
Also note that in case a row contains more than one value from other lines, the highest row wins (not the first value). If you want to match the first element, then replace the line that defines D with these three lines:
E = ~Z & 0~=diff([1:S(2);R],1,1);
E(1,:) = all(E==0,1);
D = A(R(E & cumsum(E,1)==1))
creates:
out =
8 8 8 8 0
14 14 14 14 0
8 8 8 8 8
14 14 14 0 0
Matlab User
Matlab User 2016년 2월 1일
Thank you very much, it is very much appreciated!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by