function with multiple intervals
35 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
4 Comments
Dave B
on 1 Aug 2021
You created x and y as column vectors, and then put them into one long column. I think for fprintf you want a column for each row that it will write:
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);
x y
0.00 0.00000000
0.40 0.80000000
0.80 1.60000000
1.20 2.00000000
1.60 2.00000000
2.00 1.10670000
2.40 1.05740000
2.80 1.01740000
3.20 0.91350000
3.60 0.92250000
4.00 0.93060000
(alternatively, just make x as a row vector above):
x = (0:0.4:4);
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!