Skipping calculations using if

Hello,
I have the following code:
for j = 1:(length(acalc)-1)
for ii = (j+1):length(acalc)
dotp(count2,:) = dot(acalc(j,:),acalc(ii,:));
magp(count2,:) = mag(j)*mag(ii);
count2 = count2 + 1;
end
end
Which works fine if length(acalc) > 1. However when length(acalc) = 1 (as it sometimes is), an error is returned presumably because of the failure in accessing acalc(ii,:) = acalc(j+1,:) = acalc(2,:)
Could someone help me resolve this issue? i.e. by simply skipping the calculations if length(acalc) = 1?
I tried simply stating if length(acalc) > 1 before this section of code, but that didn't seem to work.
Many thanks,
Tom

回答 (1 件)

Matt J
Matt J 2013 年 12 月 3 日

0 投票

No, if length(acalc)=1, the code you've shown would never be executed. For example, running the following will not result in anything displayed.
acalc=10;
for j = 1:(length(acalc)-1)
disp 'Executing'
end

4 件のコメント

Tom
Tom 2013 年 12 月 3 日
Ok. Well the error being returned is:
"Attempted to access acalc(2,:); index out of bounds because size(acalc)=[1,3]."
Does that not seem to imply that the way I've written the code is asking it to access a row of acalc which doesn't exist?
Matt J
Matt J 2013 年 12 月 3 日
編集済み: Matt J 2013 年 12 月 3 日
Yes. Since acalc is 1x3 it has one row, but you are trying to access a second row acalc(2,:).
Tom
Tom 2013 年 12 月 3 日
I thought that was the problem. But the problem is that most of the time (that section of the code is within a loop of its own) acalc consists of 4 or more rows and then everything is fine. What would be the way to skip those calculations for when acalc consists of only 1 row? I thought it would simply be if length(acalc) = 1 ... end. But that didn't work...
Matt J
Matt J 2013 年 12 月 3 日
編集済み: Matt J 2013 年 12 月 3 日
It doesn't look like length(acalc) is the command you should be using if you really intend to measure the number of rows. You should be using size(acalc,1) instead.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

Tom
2013 年 12 月 3 日

編集済み:

2013 年 12 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by