How to import array into fsolve function
显示 更早的评论
For asking my question I desined a very simple function:
function F = solve(x,a)
F(1) = x(1)-a;
F(2) = x(2)-3;
end
I want to solve the above function with fsolve function for an array (I know that the above function is super simple but I want to find out how to solve using fsolve for an array)
a = [1, 2];
fun = @(x)solve(x,a);
x0 = [1, 1];
x = fsolve(fun, x0)
When a is not a matrix, there is no problem but when a would be a = [1, 2] or any other matrix there is an error.
Could we do it using matlab?
The problem can be solved like the following using a for loop but can I do it without for loop?
a = [1, 2];
for i=1:2
fun = @(x)solve(x,a(i));
x0 = [1, 1];
x = fsolve(fun, x0)
x1(i) = x(1)
x2(i) = x(2)
end
回答(1 个)
Walter Roberson
2022-2-16
You have three choices:
- for loop
- hidden for loop using arrayfun (convenient)
- redesign the way you create your function to be able to effectively calculate a number of different functions at the same time, and then use a single fsolve call.
For example you could pass in a vector of a values and use something like
F = [x(2) - 3;
x(:) - a(1:7);
3*x(6:7) + x(2:3) - a(8:9)]
and so calculate a number of different things in parallel.
类别
在 帮助中心 和 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!