keeping elements with specific conditions in a matrix

7 Ansichten (letzte 30 Tage)
FATEMEH
FATEMEH am 14 Sep. 2012
Hello,
In matrix A, I need the first value of each column which is not 999. If in any column all values are 999, then I take 999. I want to avoid loops. Matrix A can have different sizes. So, I am looking for B here
A=[.1 999 999 999;
.3 .8 999 999;
.1 .2 .3 999]
B=[.1 .8 .3 999]

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 14 Sep. 2012
Bearbeitet: Andrei Bobrov am 17 Sep. 2012
s = size(A);
B = A(rem(s(1) - sum(A ~= 999),s(1))+1 + s(1)*(0:s(2)-1));
ADD
t = A ~= 999;
tt = any(t);
out = 999*~tt;
[ii,jj] = find(t);
[b,b] = unique(jj,'first');
out(tt) = A(ii(b) + size(A,1)*(jj(b)-1));
or
out = repmat(999,1,size(A,2));
[ii,jj] = find(A ~= 999);
i1 = accumarray(jj,ii,[],@min);
idx = i1 + (0:max(jj)-1)'*size(A,1);
out(i1>0) = A( idx(i1>0));
or
t = A ~= 999;
[jj,jj] = find(t);
out = accumarray(jj(:),A(t(:)),[],@(x)x(1)); % corrected
out = out + 999*~out
  4 Kommentare
FATEMEH
FATEMEH am 17 Sep. 2012
thanks a lot. the only problem is that your code does not work if A has only one row

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Azzi Abdelmalek
Azzi Abdelmalek am 14 Sep. 2012
Bearbeitet: Azzi Abdelmalek am 14 Sep. 2012
B=~(A==999)
res=[];
for k=1:size(B,2);
res=[res ;A(max([1 ;find(B(:,k)==1,1)]),k)];
end
res=res'
  2 Kommentare
FATEMEH
FATEMEH am 17 Sep. 2012
thanks a lot. do you have any suggestion to do this without loop. that will save my time a lot.
Azzi Abdelmalek
Azzi Abdelmalek am 17 Sep. 2012
ok try this
B=~(A==999);
[n,m]=size(B);
q =mat2cell(B,n,ones(1,m))
idx=cell2mat(cellfun(@(x) max([1 find(x,1,'first')]),q ,'uni',false))
B=A(idx+(0:m-1)*n)

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by