Borrar filtros
Borrar filtros

Applying a function across multiple columns

3 visualizaciones (últimos 30 días)
Allie
Allie el 1 de Mzo. de 2019
Comentada: Allie el 4 de Mzo. de 2019
I have a 12012x10000 matrix (N_red_noise) and I'm trying to choose every 12th value out of each row. I can easily do this when the matrix is 12012x1 using the code below.
N=12
X=N_red_noise(1:N:12012);
However, I cannot seem to apply this code across all 10000 columns. I've tried the following code but it does not work.
N=12
for i=1:12012
for j=1:10000
X(i,j)=N_red_noise(1:N:12012,j);
end
end
% I've also tried
N=12
for i=1:12012
for j=1:10000
X(i,j)=N_red_noise(i:N:i+12011,j);
end
end
Can someone help me figure out how to apply this to all 10000 columns? I am also open to a way to do this without loops if possible. The loops seem to take a long time to complete across this many columns

Respuesta aceptada

Guillaume
Guillaume el 1 de Mzo. de 2019
Editada: Guillaume el 1 de Mzo. de 2019
Loops certainly not needed:
X = N_red_noise(1:N:end, :);
: for the columns tells matlab, do it for all the columns. Note that I've replaced your 12012 by end which tells matlab to use the height whatever it is, so the code works regardless of the size of N_red_noise. Avoid hardcoding sizes, let matlab figure it out for you, that way you don't need to change anything if later on your array comes with a different size.
  3 comentarios
Guillaume
Guillaume el 4 de Mzo. de 2019
end is just a shortcut keyword for the last element of the array in the dimension being indexed. So, for a vector, there's no difference with length(vector) except for a theoretical insignificant speed gain (no function call to length). It's just shorter and clearer.
Plus considering that length is probably one of the most misused matlab function (people often use it on matrices where they don't know how it works), it's a lot safer. It's always equivalent to size(array, dimension_being_indexed)
Allie
Allie el 4 de Mzo. de 2019
This was really helpful. Thank you!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by