for loop with linspace

159 views (last 30 days)
Rob
Rob on 9 Feb 2018
Commented: Sebastian Castro on 10 Feb 2018
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 Comments
Image Analyst
Image Analyst on 9 Feb 2018
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 on 9 Feb 2018
Notice that
for i =length(x)
executes exactly once, with i = 100 (that is, the length of x)

Sign in to comment.

Answers (1)

Sebastian Castro
Sebastian Castro on 9 Feb 2018
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 Comments
Rob
Rob on 10 Feb 2018
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 on 10 Feb 2018
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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!