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]

1 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 17 日
編集済み: Azzi Abdelmalek 2012 年 9 月 17 日
FATEMEH, have you tried my code?

サインインしてコメントする。

 採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 9 月 14 日
編集済み: Andrei Bobrov 2012 年 9 月 17 日

0 投票

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 件のコメント

FATEMEH
FATEMEH 2012 年 9 月 17 日
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]
]
Andrei Bobrov
Andrei Bobrov 2012 年 9 月 17 日
see ADD in my answer (corrected)
FATEMEH
FATEMEH 2012 年 9 月 17 日
thanks a lot. the only problem is that your code does not work if A has only one row
Andrei Bobrov
Andrei Bobrov 2012 年 9 月 17 日
see last part my answer

サインインしてコメントする。

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 14 日
編集済み: Azzi Abdelmalek 2012 年 9 月 14 日

0 投票

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 件のコメント

FATEMEH
FATEMEH 2012 年 9 月 17 日
thanks a lot. do you have any suggestion to do this without loop. that will save my time a lot.
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 17 日
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 ExchangeMathematics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by