# Applying a function across multiple columns

13 views (last 30 days)
Allie on 1 Mar 2019
Commented: Allie on 4 Mar 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

Guillaume on 1 Mar 2019
Edited: Guillaume on 1 Mar 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.

Allie on 1 Mar 2019
That works beautifully. I originally had the code below for doing this on a 12012x1 vector.
X=N_red_noise(1:N:length(N_red_noise))
Is there a difference in how the end term functions versus the length(N_red_noise) term?
Guillaume on 4 Mar 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 on 4 Mar 2019
This was really helpful. Thank you!