keeping elements with specific conditions in a matrix

6 visualizaciones (últimos 30 días)
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]

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 14 de Sept. de 2012
Editada: Andrei Bobrov el 17 de Sept. de 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 comentarios
FATEMEH
FATEMEH el 17 de Sept. de 2012
thanks a lot. the only problem is that your code does not work if A has only one row
Andrei Bobrov
Andrei Bobrov el 17 de Sept. de 2012
see last part my answer

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 14 de Sept. de 2012
Editada: Azzi Abdelmalek el 14 de Sept. de 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 comentarios
FATEMEH
FATEMEH el 17 de Sept. de 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 el 17 de Sept. de 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)

Iniciar sesión para comentar.

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by