From a matrix, remove a number from each row (in this case " Inf " )

1 visualización (últimos 30 días)
Hello Matlab practitioner...I have a matrix a =
3 4 Inf 2
3 4 1 Inf
4 Inf 1 2
I want a matrix
b =
3 4 2
3 4 1
4 1 2
where each Inf in every row is removed. There is exactly one Inf in every row.
Thank you.

Respuesta aceptada

Rik
Rik el 18 de Feb. de 2018
I tested it with an extra row:
A=[ 3 4 Inf 2
3 4 1 Inf
4 Inf 1 2
4 4 4 Inf];
temp_A=A';
temp_A(isinf(temp_A))=[];
A=reshape(temp_A,size(A,2)-1,size(A,1))';
  1 comentario
Rik
Rik el 18 de Feb. de 2018
A speedtest of my method, the method Image Analyst suggested, and another one:
Elapsed time is 0.000539 seconds.
Elapsed time is 0.000616 seconds.
Elapsed time is 0.001997 seconds.
code:
tic
A=[3 4 Inf 2
3 4 1 Inf
4 Inf 1 2
4 4 4 Inf];
temp_A=A';
temp_A(isinf(temp_A))=[];
A=reshape(temp_A,size(A,2)-1,size(A,1))';
toc
tic
m=[3 4 Inf 2
3 4 1 Inf
4 Inf 1 2
4 4 4 Inf];
[rows, columns] = size(m);
infLocations = isinf(m);
out=zeros(rows,columns-1);
for row = 1 : rows
out(row,:) = m(row, ~infLocations(row, :));
end
toc
tic
mat=[3 4 Inf 2
3 4 1 Inf
4 Inf 1 2
4 4 4 Inf];
mat=mat2cell(mat,ones(size(mat,1),1),size(mat,2));
mat=cellfun(@(x) x(~isinf(x)),mat,'UniformOutput',false);
mat=cell2mat(mat);
toc

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 18 de Feb. de 2018
Here's another way:
m=[...
3 4 Inf 2
3 4 1 Inf
4 Inf 1 2]
[rows, columns] = size(m);
infLocations = isinf(m)
for row = 1 : rows
out(row,:) = m(row, ~infLocations(row, :))
end
out % Print to command window.
  3 comentarios
Image Analyst
Image Analyst el 19 de Feb. de 2018
I chose not to. Often times I don't preallocate when dealing with such tiny arrays. Preallocation takes time also. I got around 0.000013 to 0.000014 seconds when not preallocating, and tried it hundreds of times with preallocation and always got a longer time of around 0.000014 to 0.000020 when preallocating.
Anthony Klinkert
Anthony Klinkert el 19 de Feb. de 2018
Image Analyst, this looks good too! Thanks!

Iniciar sesión para comentar.

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by