What is valid matlab syntax in if statement?

3 ビュー (過去 30 日間)
Clarisha Nijman
Clarisha Nijman 2018 年 7 月 17 日
コメント済み: Clarisha Nijman 2018 年 7 月 17 日
If I use "==" in the 9th line of this code it says: inappropiate use of == operator. If I use "=" I am getting a parse error.
CODE:
for j=3:size(A,2)
StartTijd=A(1,2);
tijdIndex=1;
for i=1:(size(A,1)-1)
if (A(i,j)-A(i+1,j))==1
Parkingtime(tijdIndex,j)=A(i+1,2)-tijd;%service time
tijd=(A(i+1,2));
else
A(i,j)-A(i+1,j)==-1;
StartTijd=A(i+1,2);
tijdIndex=i+1;
if Parkingtime(i+1,j)<0
Parkingtime(i+1,j)=0;
end
end
end
end
[SL: applied code formatting. Clarisha Nijman, in the future please use the {}Code button to format your code so it's easier to read.]
  1 件のコメント
Pawel Jastrzebski
Pawel Jastrzebski 2018 年 7 月 17 日
編集済み: Pawel Jastrzebski 2018 年 7 月 17 日
In your 'if' you're checking for the condition, hence '=='
if (A(i,j)-A(i+1,j))==1
And also you've got whole left side encompassed with the bracket (you don't have that with the 'else' bit)
if (L-side expression) == 1
Now further down the code, if 'if' not met, the code executes 'else' bit. In my opinion there's no reason for the comparison - it's the consequence of 'if' not being met. I think the code should like like this:
(A(i,j)-A(i+1,j)) = -1;
Which is simply assigning -1 to the expression on the left hand side.

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

採用された回答

Steven Lord
Steven Lord 2018 年 7 月 17 日
What do you expect line 9, which is A(i,j)-A(i+1,j)==-1;, to do? Do you want to run lines 10-15 only if that condition is satisfied? If so, what you should do depends on whether A(i, j)-A(i+1, j) can only take on the values 1 or -1 or if it can take on other values (like 0) as well.
If that difference can ONLY be 1 or -1, you don't need the check. If you reach the else you know the difference was not 1, so by process of elimination it must be -1.
If the difference can be something other than 1 or -1, you probably want to use an elseif statement. The first example on the documentation page for the if keyword shows how to use elseif to check for a series of conditions in turn.
  1 件のコメント
Clarisha Nijman
Clarisha Nijman 2018 年 7 月 17 日
Thank you for the feedback. It helped me. The problem was indeed the if. Instead of else it should be elseif. The difference can take value -1, 0, and 1. If the difference equals zero I do not want matlab to do anything.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by