How can i plot with if statement ?
1 次查看(过去 30 天)
显示 更早的评论
>> x=[10 20 30 40 50 ] ;
>> if x==10
y=((10*10^6)*.1523)./ x ;
end
if x==20
y=((10*10^6)*.601)./ x ;
end
if x==30
y=((10*10^6)*1.914)./ x ;
end
if x==20
y=((10*10^6)*.601)./ x ;
end
if x==30
y=((10*10^6)*1.914)./ x ;
end
if x==40
y=((10*10^6)*2.73)./ x ;
end
if x==50
y=((10*10^6)*5.5547)./ x ;
end
0 个评论
回答(1 个)
Star Strider
2020-1-16
Try this:
x=[10 20 30 40 50 ] ;
for k = 1:numel(x)
if x(k)==10
y(k)=((10*10^6)*.1523)./ x(k) ;
end
if x(k)==20
y(k)=((10*10^6)*.601)./ x(k) ;
end
if x(k)==30
y(k)=((10*10^6)*1.914)./ x(k) ;
end
if x(k)==20
y(k)=((10*10^6)*.601)./ x(k) ;
end
if x(k)==30
y(k)=((10*10^6)*1.914)./ x(k) ;
end
if x(k)==40
y(k)=((10*10^6)*2.73)./ x(k) ;
end
if x(k)==50
y(k)=((10*10^6)*5.5547)./ x(k) ;
end
end
figure
plot(x, y)
grid
It is necessary to index into both ‘x’ and ‘y’ to do what you want.
1 个评论
Guillaume
2020-1-16
Note (to the OP) that 10*10^6 is better written as 10e6.
A much better design of the above would be:
LUT = [10, 0.1523; ...Look Up Table for x and corresponding coefficiet
20, 0.601;
30, 1.914;
40, 2.73;
50, 5.5547];
x = [10 20 30 40 50];
for k = 1:numel(x)
[found, whichrow] = ismember(x(k), LUT(:, 1));
if found
y(k) = 10e6 * LUT(whichrow, 2) / x(k);
else
error('don''t know how to calculate y(k)');
end
end
figure;
plot(x, y);
grid;
So now if you want to add/remove x values and coefficients you only have one line of a matrix to edit instead of having to copy-paste/delete several lines of codes. It's also a lot clearer what the coefficient are and it avoids having twice the same tests (e.,g. the 20 and 30 test that was repeated originally).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!