Save values in a matrix using a non-integer index
Show older comments
Hello all! i have a major problem in matlab and although i read all the answers couldn't solve this. my code is:
%Moments calculation along beam
%Vertical forces
Oy = 1260.1; %[KN]
N1 = 210.5; %[KN]
N2 = 252.8; %[KN]
N3 = 289; %[KN]
N4 = 316.8; %[KN]
N5 = 191; %[KN]
%Position where the forces are implemented
x1 = 16.68; %[m]
x2 = 16.78; %[m]
x3 = 17.89; %[m]
x4 = 16.93; %[m]
x5 = 17.15; %[m]
x6 = 0.936; %[m]
%Moment at start position
Mo = -64758.212; %[KNm]
%Calculation
for x=0:0.1:85.43
if x == 0
M = Mo;
elseif x <= x1
M = Mo + Oy*x;
elseif x1 < x <= (x1+x2)
M = Mo + Oy * x - N1*x1;
elseif (x1+x2) < x <= (x1+x2+x3)
M = Mo + Oy*x - N1*(x1+x2) - N2*x2;
elseif (x1+x2+x3) < x <= (x1+x2+x3+x4)
M = Mo + Oy*x - N1*(x1+x2+x3) - N2*(x2+x3) - N3*x3;
elseif (x1+x2+x3+x4) < x <= (x1+x2+x3+x4+x5)
M = Mo + Oy*x - N1*(x1+x2+x3+x4) - N2*(x2+x3+x4) - N3*(x3+x4) - N4*x4;
end
end
i want to save all the moments (M) in a matrix in order to use it in another equation but M(x) is incorrect as x is a non-integer number. Any help would be really appreciated!!!!
4 Comments
Theodoros Pardalakis
on 28 Feb 2016
Why not index it instead of with x but with the index of x?
x_vals=0:0.1:85.43;
M_out = zeros(length(x_vals),1)
Then at the end of your loop do
M_out(find(x_vals==x,1)) = M;
Would something like that work? In this situations, row i of M_out corresponds to row i of x_vals so you can back out the relevant values.
As an aside, this is usually why when you write for loops it's a good idea to index with integers when possible.
Steven Lord
on 1 Mar 2016
FYI this doesn't do what you think it does.
x1 < x <= (x1+x2)
- If x1+x2 is greater than or equal to 1 this is always true.
- If x1+x2 is greater than or equal to 0 but less than 1, this is ~(x1 < x).
- If x1+x2 is less than 0 this is always false.
You need to use something like this to do what you want:
(x1 < x) & (x <= (x1+x2))
Theodoros Pardalakis
on 1 Mar 2016
Accepted Answer
More Answers (2)
the cyclist
on 29 Feb 2016
You can also do the whole calculation in a vectorized fashion, by replacing the conditional statement like this:
MM = Mo + (x<=x1).*Oy.*x - (x<=(x1+x2)).*N1*x1 ... % and so on
Theodoros Pardalakis
on 1 Mar 2016
0 votes
2 Comments
Theodoros Pardalakis
on 1 Mar 2016
the cyclist
on 1 Mar 2016
Did you carefully read and understand Steven Lord's comment? It is almost certainly the case that your if-else statements are not doing what you think.
Categories
Find more on Creating and Concatenating Matrices 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!