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

1 view (last 30 days)
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.

Accepted Answer

Rik
Rik on 18 Feb 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 Comment
Rik
Rik on 18 Feb 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

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 18 Feb 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 Comments
Image Analyst
Image Analyst on 19 Feb 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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!