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

3 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 8 Dec 2022
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 Comments
Alex
Alex on 8 Dec 2022
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 on 8 Dec 2022
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

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!