필터 지우기
필터 지우기

how to shorten this equation?

조회 수: 1 (최근 30일)
Selin Soguksu
Selin Soguksu 2012년 5월 8일
Hello, I want to ask a question. I'm very new on MATLAB. I have a matrix called K. K(100,40) 100 rows and 40 columns. Matrix includes only 0 or 1. I wrote an equation like this:
İ=0; J=0;
for i=0:99
form1(i+1,1)=K(i+1,j+1)+K(i+1,j+3)+K(i+1,j+5)+K(i+1,j+7)+K(i+1,j+9)+ ..... +K(i+1,j+39);
form2(i+1,1)=K(i+1,j+2)+K(i+1,j+4)+K(i+1,j+6)+K(i+1,j+8)+K(i+1,j+10)+ .... + K(i+1,j+40);
end
And my problem , for j is 1 to 40 so I'm writing too much code. How can I shorten this equation? Is there a way, please help me?

채택된 답변

Oleg Komarov
Oleg Komarov 2012년 5월 8일
Sum for each row the odd columns (form1) and the even columns (form2):
form1 = sum(K(:,1:2:end),2);
form2 = sum(K(:,2:2:end),2);
You don't need a loop.
Please read the Getting Started Guide and specifically: Indexing::Language Fundamentals
  댓글 수: 1
Daniel Shub
Daniel Shub 2012년 5월 8일
This doesn't make use of the logical (0 or 1) nature of K, but I cannot think of a loopless (no arrayfun either) one line solution that uses the logical aspect...

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

추가 답변 (1개)

Selin Soguksu
Selin Soguksu 2012년 5월 8일
Thank you very much for your answer. It works great :))

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by