keeping elements with specific conditions in a matrix

16 views (last 30 days)
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]

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 14 Sep 2012
Edited: Andrei Bobrov on 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 Comments
FATEMEH
FATEMEH on 17 Sep 2012
thanks a lot. the only problem is that your code does not work if A has only one row

Sign in to comment.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 14 Sep 2012
Edited: Azzi Abdelmalek on 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 Comments
FATEMEH
FATEMEH on 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 on 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)

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!