Applying a function across multiple columns

3 次查看(过去 30 天)
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
Guillaume 2019-3-1
编辑:Guillaume 2019-3-1
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 个评论
Guillaume
Guillaume 2019-3-4
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)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by