How to make a for loop for fzero solved functions?
3 ビュー (過去 30 日間)
古いコメントを表示
Im having some issues making a loop for fzero functions. Basically I want a code that solves for x(i+1) and then uses that value to solve for the next equation
function y=fncsys(x)
x(1)=0.3
y=0
for i=1:4
y = 5(x(i)-x(i+1)) +10((x+i)^2)
end
fzero(@fncsys, 1)
1 件のコメント
Walter Roberson
2024 年 9 月 12 日
y = 5(x(i)-x(i+1)) +10((x+i)^2)
First of all: that code is inside a for loop, and that code overwrites all of y each iteration. The end result of the loop would have a y corresponding to the highest loop iteration, as if only for i=4 had been executed.
Secondly: the above code requests that the constant 5 be indexed by the floating point value of the expression x(i)-x(i+1) . MATLAB does not allow constants to be indexed by anything. MATLAB has absolutely no implied multiplication: something of the form A(B) is always either function evaluation or indexing.
Thirdly: at the first iteration of the loop, x(1) has been initialized, but you attempt to evaluate x(i+1) where i = 1, so you attempt to evaluate x(2) . That will fail because x(2) has not been set to anything.
回答 (1 件)
Rahul
2024 年 9 月 12 日
I understand that you wish to obtain a code that solves for 'x(i+1)' during each iteration and then similarly uses that value to solve for the next one.
You can use 'current' and 'next' variables in your code to solve the loop iteratively along with using 'fzero' function handle in the loop.
Here is an example:
% Preallocate array 'x'
x = zeros(1, 4);
x(1) = 0.3;
for i = 1:4
% Function handle for 'fzero', passing 'current' and 'next' value of 'x'
fncsys = @(x_next) 5 * (x_current - x_next) + 10 * ((x_current + i)^2);|
% Updating the 'next' value of 'x'
x_next = fzero(fncsys, x_current);
% Updating the 'i+1'th and 'current' value of 'x'
x(i+1) = x_next;
x_current = x_next;
end
% I have used 'x_next' and 'x_current' variables to update the
% 'next' and 'current' values of 'x' respectively.
This code allows updating the 'x(i+1)' values iteratively using the for loop as desired.
You can refer to the following Mathworks documentationz to know more about these functions:
'Function Handles': https://www.mathworks.com/help/releases/R2024a/matlab/function-handles.html?searchHighlight=function%20handles&s_tid=doc_srchtitle
Hope this helps!
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!