Pre-allocating speed for an array that change size on every loop iteration

3 ビュー (過去 30 日間)
Alex
Alex 2022 年 12 月 8 日
コメント済み: Walter Roberson 2022 年 12 月 8 日
I have got a big matrix (1000x1000 for instance) and I want to get all the elements of the even columns. So I create that loop, but because of the lack of speed, it never gets finished.
Matrix = randi([0, 1], [1000,1000]);
[row,column]=size(Matrix);
VectorValue=[];
for i=1:1:row
for j=1:2:column
ValueEven=Matrix(i,j); %Get the value of actual even column
VectorValue=[VectorValue, ValueEven]; %Put that value in an array of all the values of the even columns
end
end

採用された回答

Walter Roberson
Walter Roberson 2022 年 12 月 8 日
Matrix(:,2:2:end)
would give you a 1000 x 500 matrix extracted from the even columns. You could reshape() that if there was reason to do so.
  2 件のコメント
Alex
Alex 2022 年 12 月 8 日
Thank you, it works. But I have many other functions with that same issue and I would like to know how to solve it by Pre-allocating.
Walter Roberson
Walter Roberson 2022 年 12 月 8 日
cols_out = floor(size(Matrix,2)/2);
output = zeros(size(Matrix,1), cols_out, 'like', Matrix);
for idx = 1:cols_out
output(:,idx) = Matrix(:,idx*2);
end

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by