function with multiple intervals

2 views (last 30 days)
Touts Touts on 31 Jul 2021
Commented: Touts Touts on 2 Aug 2021
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 on 31 Jul 2021
Edited: Dave B on 31 Jul 2021
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
Touts Touts on 2 Aug 2021
@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!