How do I display only certain numbers from a plot?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
This is for a begineer Matlab class assignment so bear with me here. The assignment is to plot a graph of a first order equation, then based on the persison set by the user, it needs to tell you which x values y is equal to zero at. The problem I am having is that I get an error with my if statement and I dont know how to fix it. All I need it to do is check if there are y values between the set persison and then display the x value at that point.
clc
clear
a=input('What is the value of a? ');
b=input('What is the value of b? ');
r=input('What is the range? ');
s=input('What is the step-size for range of x ');
p=input('What is the persison of zero? ');
x=-r:s:r;
y=(a*x)+b;
plot(x,y,'r*')
if -p<y && y<p
fprintf('Y=0 at x=%f',y)
else
disp('Error. Enter a new range or persison')
end
5 Kommentare
Cris LaPierre
am 18 Apr. 2023
a=1;
b=0;
r=10;
s=0.1;
p=0.5;
x=-r:s:r;
y=(a*x)+b;
plot(x,y,'r*')
if -p<y && y<p
fprintf('Y=0 at x=%f',y)
else
disp('Error. Enter a new range or persison')
end
Antworten (2)
Dyuman Joshi
am 18 Apr. 2023
Verschoben: Walter Roberson
am 18 Apr. 2023
"&&" can only be used when then result of each logical expression is a scalar (as the error states as well), in all other cases you need to use a single AND "&" operator.
It's not clear if you want to compare each values of y seperately or all together? In case you want to compare all values, you need to use all() (again stated in the error). Here you can use &&, as the output of these expressions will be a scalar
if all(-p<y) && all(y<p)
0 Kommentare
Walter Roberson
am 18 Apr. 2023
Your y is a vector. You want to find locations in that vector that are between -p and +p .
mask = -p < y & y < p;
Now you have a few different possibilities to consider:
- all entries in mask might be false -- ~any(mask) . In this case either there were no roots or the step size is too large or the precision is too small
- exactly one entry in mask might be true -- nnz(mask) == 1. In this case you have successfully found one root at x(mask)
- there might be one grouping in mask where several entries in a row are true. This can happen if the precision is too large and the function is not changing faster than the precision would suggest
- there might be several distinct places in mask where exactly one entry is true. This would typically correspond to multiple roots of the equation
- you might have false roots. For example x.^2 + 1e-7 has no true roots over reals, but if your precision were 1e-6 then you would think that you found a root,
0 Kommentare
Siehe auch
Kategorien
Mehr zu Programming Utilities finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
