keeping elements with specific conditions in a matrix

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]

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 9월 14일
편집: Andrei Bobrov 2012년 9월 17일
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

this is nice, but if I change A to the following, it does not work
A=[.1 999 .5 999;
.3 .8 999 999;
.1 .2 .3 999]
]
see ADD in my answer (corrected)
thanks a lot. the only problem is that your code does not work if A has only one row
see last part my answer

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2012년 9월 14일
편집: Azzi Abdelmalek 2012년 9월 14일
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

thanks a lot. do you have any suggestion to do this without loop. that will save my time a lot.
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)

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

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by