problems with "if statement"
显示 更早的评论
Hi everyone. I am beginning in Matlab and I have a problem.
My code follows:
for i=1:Nped
for j=1:length(t)
dist(i,j)=vp(i)*t(j);
for k=1:NH
if (dist(i,j)<=Lenght)
Findiv(i,:)=G(i)+alfadin(1)*G(i)*sin(2*pi*i*fp(i)*(t-Tentr(i))-phase(1));
else
Findiv(i,:)=0
end
end
end
For some reason, the loop :
if (dist(i,j)<=Lenght)
.... is not been well executed. I ploted the graphic of dist(1,j) vs t (time) and I verified that for a distance dist(1, j ) > lenght (where lenght= 20 m), the non-zero expression give by
Findiv(i,:)=G(i)+alfadin(1)*G(i)*sin(2*pi*i*fp(i)*(t-Tentr(i))-phase(1))
is not calculated (as showed in the second graph).

Does anyone could help me to solve this problem?
Thanks a lot =)
4 个评论
Image Analyst
2022-3-13
What is Lenght, lenght, and length? Those are three different spellings and capitalizations and MATLAB is sensitive to mispellings and is case sensitive. Also, where is your plotting code?
Torsten
2022-3-13
Where do the loop variables "k" and "j" come into play within the k-loop ?
As written, the k-loop is superfluous.
Igor Braz Gonzaga
2022-3-13
Jan
2022-3-14
In this version "phase(k)" appears. In the version you post in the comments below, it is "pahse(1)". This optimizes the cofusion fro the readers. We see 3 different codes now and all of them do, what they are doing. You are expecting something else, but we cannot guess why.
Use the debugger to examine whats going on. Set a breakpoint in the first line, then step through the code line by line. Of course, Matlab does exactly what it is instructed to do. The IF condition does work properly, so the only problem is that you expect something else.
The purpose if the "for k=1:NH" loop is still not clear and inside it Findiv is overwritten repeatedly. This cannot be useful.
采纳的回答
更多回答(1 个)
Voss
2022-3-14
0 个投票
A couple of people have pointed out that the "for k=1:NH" loop is not necessary, but since it is still part of the code, can you check the value of NH?
If NH is less than 1 or NH is the empty array, then the "for k=1:NH" loop will execute zero times, leading to the if statement not being checked at all and Findiv not being calculated (but dist will be calculated because that is done outside the "for k=1:NH" loop).
This possibility is consistent with your observations of the values of dist and Findiv, if Findiv is pre-allocated with zeros.
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
