for loop with linspace

165 ビュー (過去 30 日間)
Rob
Rob 2018 年 2 月 9 日
コメント済み: Sebastian Castro 2018 年 2 月 10 日
Hi all, I'm trying to get the following for loop statement to work. I'm doing shear force calculations for different portions of a beam. I get this as error 'Subscript indices must either be real positive integers or logicals'.
b =input('Enter the length of the beam ');
u =input('Enter the load (N/m) ');
R_side = u*b/3;
R_center = R_side;
d = 0.17 * b;
l = 0.33 *b;
x = linspace(0,b,100);
for i =length(x)
if i<= d
sh(i) = -u*x;
elseif x<= d+l
sh(i) = -u*x + R_side;
elseif x<= d+2*l
sh(i) = -u*x + R_side + R_center;
else
sh(i) = -u*x + R_center + 2*R_side;
end
end
plot(x,sh(i))
xlabel(' Length of beam, [m]','FontSize',20);
ylabel(' Shear force, [N]','FontSize',20);
title('Shear Force Diagram','FontSize',20);
  2 件のコメント
Image Analyst
Image Analyst 2018 年 2 月 9 日
Not what I get:
Enter the length of the beam 4
Enter the load (N/m) 5
Subscripted assignment dimension mismatch.
Error in test4 (line 21)
sh(i) = -u*x + R_center + 2*R_side;
What values did you enter?
Walter Roberson
Walter Roberson 2018 年 2 月 9 日
Notice that
for i =length(x)
executes exactly once, with i = 100 (that is, the length of x)

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

回答 (1 件)

Sebastian Castro
Sebastian Castro 2018 年 2 月 9 日
I see 2 things here
First, the for-loop should start from the first index and stop at the length of x. Right now, your code is saying that i is only one value ( length(x) ).
for i=1:length(x)
Secondly, just as you're assigning each individual element of the sh vector as sh(i), you want to do the same with x instead of trying to perform operations on the entire array. So, for example:
sh(i) = -u*x(i)
- Sebastian
  2 件のコメント
Rob
Rob 2018 年 2 月 10 日
Okay so now that I followed your corrections I'm getting a blank plot/vectors must be the same length error. Is it because I should make a vector with the output of sh? How could I store every value of sh(i)
as in save_case = 0;
save_case = save_case + 1;
sh_output(save_case) = sh?
Sebastian Castro
Sebastian Castro 2018 年 2 月 10 日
I think you need to remove the indexing from the plot, since you want the whole sh vector. The following command should do it:
plot(x,sh)
- Sebastian

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

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by