Why does my plot say undefined variable or function for X2?

1 次查看(过去 30 天)
Lv = 4.5;
Lh = 2.5;
Pmax = 83;
MaxXcvalue = 0.75;
Xc = 0.25:0.01:0.75;
Areaofvertical = (Lv*X);
Areaofhorizontal = (Lh*X);
Areaofsoil = (4.5)*(1.5);
for X = 1:Xc ;
Ww = (Unitweight)*(((Lv)*(X))+((Lh)*(X)))*1;
Leverarmofvertical = (0.5+(X/2));
Leverarmofhorizontal = (Lh/2);
Leverarmofsoil = (0.5 + (X) + (1.5/2));
Moment = ((Areaofvertical)*(Leverarmofvertical))+((Areaofhorizontal)*(Leverarmofhorizontal))+((Areaofsoil)*(Leverarmofsoil));
Totalarea = (Areaofvertical)+(Areaofhorizontal)+(Areaofsoil);
X1 = (Moment)/(Totalarea);
X2 = X1 - ((Pmax)/(Ww))*((Lv + X)/(3));
end;
plot(X, X2);
grid on;
[SL: Formatted code as code]

回答(2 个)

Jeremy
Jeremy 2020-4-30
Your code returns an undefined function or variable X error, because you try to define
Areaofvertical = (Lv*X);
before you have defined X. Maybe you meant Areaofvertical to use Xc?
  2 个评论
Ash Maxwell
Ash Maxwell 2020-4-30
I have tried that but it still does not seem to like it. When I put it in the while loop it comes up with the graph but with no values plotted.
Jeremy
Jeremy 2020-4-30
well, I think this is your problem:
Xc = 0.25:0.01:0.75;
for X = 1:Xc
I do not believe the line X = 1:Xc is doing what you think it's doing, since Xc is an array of values, not a single value. Perhaps instead, you should try
for X = Xc

请先登录,再进行评论。


Steven Lord
Steven Lord 2020-4-30
There are several problems with your code, but the main one is that your for loop body never executes.
for X = 1:Xc
Since Xc is a non-scalar, MATLAB will only use the first element of that vector when constructing the vector of values over which X iterates. So the loop will run once per element of this vector:
iterates = 1:0.25
You probably want to have X iterate from 1 to the numel of Xc, operating on element X of Xc in turn and assigning into element X of X2.
  2 个评论
Ash Maxwell
Ash Maxwell 2020-4-30
编辑:Ash Maxwell 2020-4-30
I understand how it iterates one, but I don't quite understand what you mean for the solution. Could you perhaps explain it in Layman's terms? Thank you so much for the suggestion!
Steven Lord
Steven Lord 2020-4-30
x = randperm(10, 5); % random selection (without replacement) of 5 elements in 1:10
y = x.^2;
for k = 1:numel(x)
fprintf("%d squared is %d.\n", x(k), y(k))
end
If I'd iterated over x, I could have asked for say the 10th element of x and y, but they'll only have 5 elements.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by