Why does this code output all values as 1?

조회 수: 4 (최근 30일)
BOB
BOB 2019년 6월 6일
답변: John D'Errico 2019년 6월 6일
Hi there, I'm trying to program a piecewise geometric function into matlab:
I have written the code as follows. If anybody can explain why the output (Sij) always equals 1 when I run this it would be helpful. The input "rrup" is just a bunch of random distance values ranging from 0 to 1000 (km).
decay0 = 1.0;
decay1 = 0.0;
decay2 = 2.22;
r0 = 50;
r1 = 50;
r2 = 150;
r = rrup;
for i = 1:length(r)
if r(i)<r0
Sij = (r0/r(i)).^decay0
elseif r1<=r(i)<=r2
Sij=(r1/r(i)).^decay1
elseif r(i)>r2
Sij =(r2/r(i)).^decay2
end
end

채택된 답변

Jan
Jan 2019년 6월 6일
편집: Jan 2019년 6월 6일
elseif r1<=r(i)<=r2
This will not do, what you expect. Matlab processes the expression from left to right. The first part is:
r1 <= r(i)
This is either true or false, which is converted to 1 or 0. Because r2 is 150, both values reply true for the second comparison:
(r1 <= r(i)) <= r2
You mean:
elseif r1 <= r(i) && r(i) <= r2
Now consider that you overwrite Sij in each iteration. So you get the last value as output only. Maxbe you want a vector instead? This will work easier without a loop:
decay0 = 1.0;
decay1 = 0.0;
decay2 = 2.22;
r0 = 50;
r1 = 50;
r2 = 150;
r = rrup;
S = nan(size(r));
index = (r < r0);
S(index) = (r0 ./ r) .^ decay0;
index = (r1 <= r & r <= r2);
S(index) = (r1 ./ r) .^ decay1;
index = (r > r2);
S(index) = (r2 ./ r) .^ decay2;

추가 답변 (1개)

John D'Errico
John D'Errico 2019년 6월 6일
A significant problem with your code is in your assumption that this line does what you rthink it does:
elseif r1<=r(i)<=r2
It is NOT equivalent to the line
elseif (r1<=r(i)) && (r(i)<=r2)
Yes. It is common mathematical shorthand for the two tests. But it is NOT what you think it is when used in MATLAB.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by