for loop for non integer values
3 次查看(过去 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!