# function with multiple intervals

1 ビュー (過去 30 日間)
Touts Touts 2021 年 7 月 31 日
コメント済み: Touts Touts 2021 年 8 月 2 日
Dear all, why i cant plot and export the result of my equation ?
clc, clear all, close all
x = (0:0.4:4)'
%
if 0<= x && x< 1
y = 2.*x
disp('y1')
elseif 1<= x && x< 2
y = 2
disp('y2')
elseif 2<= x && x<3
y = (3/x).^(1/4)
disp('y3')
elseif 3<= x && x<=4
y = ((3/x).^(1/4))*((x/4).^(1/3))
disp('y4')
end
plot(x,y)
%
M = [x; y];
%
fileID = fopen('out.txt','w');
fprintf(fileID,'%6s %12s\n','x','y');
fprintf(fileID,'%6.2f %12.8f\n',M);
fclose(fileID);
Thanks

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

### 採用された回答

Dave B 2021 年 7 月 31 日

When you write
x = (0:0.4:4)'
%
if 0<= x && x< 1
...
end
MATLAB sees: if the number zero is less than the list of values 0, 0.4, ...
It throws an error because && is for comparing two scalars, and you've given it a scalar and a vector.
I believe what you'd like to do is compare each of the values in x to 0 (and to 1, and later to two, etc.)
There are two options, the *good* approach is to do this in a vectorized way:
x = (0:0.4:4)';
y = nan(size(x)); % initializing y is smart because it helps you to catch cases where you forgot to define what should happen for some x
y(0 <= x & x < 1) = 2.*x(0 <= x & x < 1);
y(1 <= x & x < 2) = 2;
y(2 <= x & x < 3) = (3/x(2 <= x & x < 3)).^(1/4);
y(3 <= x & x <= 4) = ((3/x(3 <= x & x <= 4)).^(1/4))*((x(3 <= x & x <= 4)/4).^(1/3));
plot(x,y)
Here I read this as y, for those x where 0 is less than or equal to x and x is less than 1, should be set two 2 times x for those x where 0 is less than x and x is less than 1, etc.
Note use of one & instead of two for comparing two vectors.
In general you can make this code look cleaner by naming an 'index' variable to hold the bit that goes in the parentheses.
The second approach, which will look more similar to your existing code, is to loop over the values in x:
x = (0:0.4:4)'
y = nan(size(x)); % initializing for the same reason as before
for i = 1:length(x)
xx = x(i);
if 0 <= xx && xx < 1
y(i) = 2.*xx;
elseif 1<= xx && xx < 2
y(i) = 2;
elseif 2 <= xx && xx < 3
y(i) = (3/xx).^(1/4);
elseif 3<= xx && xx<=4
y(i) = ((3/xx).^(1/4))*((xx/4).^(1/3));
end
end
##### 4 件のコメント表示非表示 3 件の古いコメント
Touts Touts 2021 年 8 月 2 日
@Dave B thanks very much

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

R2016a

### Community Treasure Hunt

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

Start Hunting!

Translated by