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

1 回表示 (過去 30 日間)
Anthony Klinkert
Anthony Klinkert 2018 年 2 月 18 日
コメント済み: Anthony Klinkert 2018 年 2 月 19 日
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.

採用された回答

Rik
Rik 2018 年 2 月 18 日
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 件のコメント
Rik
Rik 2018 年 2 月 18 日
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

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2018 年 2 月 18 日
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 件のコメント
Image Analyst
Image Analyst 2018 年 2 月 19 日
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 2018 年 2 月 19 日
Image Analyst, this looks good too! Thanks!

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by