Multiple values for a variable in a for loop

조회 수: 4 (최근 30일)
Christoffer Thornvall
Christoffer Thornvall 2015년 10월 5일
댓글: Christoffer Thornvall 2015년 10월 5일
Hi, I'm just trying to do something really simple but it doesn't work and I don't know why despite the error message. I'm new to matlab so be gentle.
x is a column vector (10,1) with values ranging from 0.2 to 2 with 0.2 incraments. I would like for the eq to go through each of the x values and then possibly, if someone is willing to help, to store these 10 calculated values in a new (10,1) column vector.
for x2 = x(1:10)
y1 = ((fg*x2^2)/(24*E*I))*(x2^2 - 4*L*x2 + 6*L^2)
end
Thanks in advance!
Regards Christoffer

채택된 답변

Guillaume
Guillaume 2015년 10월 5일
Assuming that fg, E, I, and L are scalar, the reason your code does not work (and you should have explained what does not work mean) is because you're always assigning the output to the same element of the same variable: y1(1) (if you don't put an index, it's assumed to be one). To solve, one possible way
for idx = 1:numel(x)
y(idx) = ((fg*x(idx)^2)/(24*E*I))*(x(idx)^2 - 4*L*x(idx) + 6*L^2);
end
However, the loop is not needed. Simply use the vectorising ability of matlab and just one line is needed:
y = ((fg*x.^2)/(24*E*I))*(x.^2 - 4*L*x + 6*L^2)
Note that I've replaced the ^ with .^ to tell matlab to apply the function elementwise.
  댓글 수: 1
Christoffer Thornvall
Christoffer Thornvall 2015년 10월 5일
oh that makes perfect sense, can't believe I missed that with the(y1). Thank you so much for explaining this. I will make sure to describe the error in detail too next time

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Purushottama Rao
Purushottama Rao 2015년 10월 5일
편집: Purushottama Rao 2015년 10월 5일
You dont need a for loop for doing it. you can try somthing like
x(1:10)=0.2:0.2:2
y1 = ((fg*x2^2)/(24*E*I))*(x2^2 - 4*L*x2 + 6*L^2)
..................................
which should result in a column vector of same size as x
  댓글 수: 2
Guillaume
Guillaume 2015년 10월 5일
편집: Guillaume 2015년 10월 5일
For that matter, you don't need to index the result of an assignment. So it's just
x = 0.2:0.2:2;
which also has the advantage of not having to worry between size mismatch between destination and source.
And of course, the code will not result in a column vector but an error because
  • you forgot to rename x2
  • you're using ^ with a vector
Christoffer Thornvall
Christoffer Thornvall 2015년 10월 5일
I will try to see if this works too, thank you!!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by