简体   繁体   中英

Return multiple solutions GNU Octave or Matlab

I have a function that solves for a variable in an equation. There should be 2 solutions to the equation. For example, 9=x^2, x can be 3 or -3. How can I get both values to be returned? Right now it only returns the first answer, 3.

You can modify your function to return an array of values, for example

function x = solve_square(y)
    % Returns the solutions to y=x^2
    x = [sqrt(y), -sqrt(y)];
end

Usage would be

>> x = solve_square(9)
x =
     3   -3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM