필터 지우기
필터 지우기

Applying a function across multiple columns

조회 수: 3 (최근 30일)
Allie
Allie 2019년 3월 1일
댓글: Allie 2019년 3월 4일
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)
Allie
Allie 2019년 3월 4일
This was really helpful. Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (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