Replacing specific values in each matrix row in all values in the matrix
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposta accettata
Stephen23
il 1 Feb 2016
Modificato: Stephen23
il 1 Feb 2016
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 Commenti
Stephen23
il 1 Feb 2016
Modificato: Stephen23
il 1 Feb 2016
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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!