for loop for non integer values
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi all, Can you help me please with this code that I stuck!? I want to solve a fifth order polynomial for values of time(t) between (1:0.3.10) I use the code below, but all the time the value of piks the integer i values ( 1,2,3,4,5,6,7,8,9,10) and it does not calculate E for non integer values(0.3, 0.6, 0.9 ...) Where is the problem? Could you please help me?
clc
clear all
syms a3 a4 a5 t
x=a3*t.^3+a4*t.^4+a5*t.^5;
for i=1:0.5:10;
x1=subs(x,t,i);
x_p=subs(diff(x,t),t,i);
x_pp=subs(diff(x,t,2),t,i);
eqns=[x1==75, x_p==0, x_pp==0];
S=solve(eqns,[a3,a4,a5]);
a3_5=S.a3;
a4_5=S.a4;
a5_5=S.a5;
L=subs(x,[a3,a4,a5],[a3_5,a4_5,a5_5]);
L_p=diff(L);
L_pp=diff(L,2);
J=0.000011*L_pp.^2;
E(i,:)=vpa(int(J,[0,i]))
digits(4);
end
댓글 수: 0
답변 (2개)
Stephen23
2024년 12월 4일
이동: Walter Roberson
2024년 12월 4일
It is usually much easier and clearer to loop over indices, rather than over data values:
V = 1:0.5:10;
E = nan(..); % preallocate!
for k = 1:numel(V)
i = V(k);
...
E(k,:) = vpa(int(J,[0,i]));
end
댓글 수: 0
ag
2024년 12월 4일
Hi Sara,
The issue that you are encountering is because integer operands are required for colon operator when used as index.
To resolve this issue, you can use a counter variable, to store the results into matrix "E". The below code demonstrates the same:
counter = 1;
for i=1:0.5:10;
% the logic
E(counter, :) = vpa(int(J, [0, i]))
counter = counter + 1;
end
Hope this helps!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!