How to use solver in function

I have got a problem here.
I want to use solver within a function I m writing. To give you more details, suppose I want to write a function like:
function [a] = example
a = solve('14 = x^2')
end
Now the problem is how I can key in a variable instead of 14 in that solver. I mean suppose I have a variable been defined before like: d = 14, now I want to write my function as below, but it doesn't work :(
function [a] = example
d = 14
a = solve('d = x^2')
end
Any help?

 Respuesta aceptada

Walter Roberson
Walter Roberson el 11 de Feb. de 2012

0 votos

syms x
a = solve(x^2 - d)
Alternately,
d = 14
a = solve(subs(sym('d = x^2'), 'd', d));

4 comentarios

Kian
Kian el 11 de Feb. de 2012
Thank you Walter for the answer.
Actually it works as you wrote it. But, I think for the case I have it does not, cause I think I wrote my issue not exactly in such a way it is. I mean you gave me a good answer, but that's just not exactly my case, so I write the equation itself, and I just put it in the shape you told me to do. So,
a = mat2(1,2);
b = mat2(1,3);
r = solve(subs(sym('a=(((1/273)-((0.0001844)*(log(((r*0.001)*b)/(0.611*((r*0.001)+0.622))))))^-1)-273'),'a',a,'b',b));
where mat2 has already been defined. According to what you said, now it should work out. But when I run the program it gives me an error saying:
??? Error using ==> sym.subs
Too many input arguments.
So, I think the problem is with the number of arguments I have in my equation(a & b). I think I didn't explain my issue well in the first place, so sorry for that.
I have got another problem relating to this issue as well.
Later I have a line as:
content = f - r;
where r is the result given by the solver, (f has already been computed), and then I have:
fid = fopen('Result.txt','wt');
fprintf(fid,'Content of the parcel is %5.2f\n',content);
fclose(fid);
Again when I run the program it gives me an error relating to this code line saying:
??? Error using ==> fprintf
Function is not defined for 'sym' inputs.
I would appreciate any help, and sorry for my lengthy question. I think I have now explained everything in detail.
Thanks again.
Walter Roberson
Walter Roberson el 12 de Feb. de 2012
Do not use subs(expression, var1, value1, var2, value2)
Instead use subs(expression, {var1, var2}, {value1, value2});
Walter Roberson
Walter Roberson el 12 de Feb. de 2012
If you have a number in symbolic form which does not contain any unresolved symbols, then use double() to convert it to double precision number. Otherwise use char() and print the result as a string.
Kian
Kian el 12 de Feb. de 2012
Thank you very much Walter. Both of the problems were solved.
Thank you again.

Iniciar sesión para comentar.

Etiquetas

Preguntada:

el 11 de Feb. de 2012

Editada:

el 8 de Oct. de 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by