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

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

 Respuesta aceptada

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 comentarios

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.
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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Productos

Versión

R2022b

Preguntada:

el 8 de Dic. de 2022

Comentada:

el 8 de Dic. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by