Azzera filtri
Azzera filtri

How can I write a mathematical function in Matlab?

5 visualizzazioni (ultimi 30 giorni)
Can I build an equation which have different components?
variables written in cell array(1x3) such as 'X1' 'X2' 'X3'
exponents written in matrix (3x3 double) e.g [0 .5 -.5; .5 -.5 0; 1 0 .5]
Parameters written in matrix(3x1) e.g [.55;.25;.6893]
can I get equation like
F= .55*X2^.5*X3^-.5+ .25*X1^.5*X2^-.5+.6893*X1^1*X3^.5
Many thanks

Risposta accettata

Walter Roberson
Walter Roberson il 25 Giu 2015
MATLAB is a general purpose programming language. You can build up any string you want.
subf = sprintf('*X%d^e%d', [1:3; 1:3]);
formula = ['a1' subf '+a2' subf '+a3' subf];
What you should try to avoid is executing such strings. Dynamic generation of code is error prone.
  32 Commenti
Walter Roberson
Walter Roberson il 30 Giu 2015
function form = generateFormula(a, e)
form = '';
for k = 1 : length(a)
thispart = sprintf('%g*X1^%g*X2^%g*X3^%g+', a(k), e(k,1), e(k,2), e(k,3));
form = [form thispart];
end
form(end) = []; %remove extra '+'
end
and the test code
%generate expression
%Use the "a" and "e" that are in your workspace!
formula = generateFormula(a, e) %it returns a string now!
I am done. I am not going to answer any more questions on this topic. Do not email me about it.
You now have the code to create the string that you wanted, and what you do with it is your problem.
ND
ND il 1 Lug 2015
Many thanks Walter for all help and I am very sorry for that you are right I should use the code that result symbolic expression . Please delete the last your comment
Many thanks

Accedi per commentare.

Più risposte (1)

Thorsten
Thorsten il 29 Giu 2015
Modificato: Thorsten il 29 Giu 2015
If X take some values and you make sure that the e and p parameters are in the order of pairs, e.g., for N = 3
1 2
1 3
2 3
You can use the following code:
e = [0.5 -.5; 0.5 -0.5; 1 0.5];
p = [.55 0.25 0.6893];
X = [345 3 27]; % array of number
% code below should work for arbitrary number N of X values,
% as long as e is N x 2 and p is 1 x N:
N = numel(p);
pairs = nchoosek(1:N, 2);
F = 0;
for i=1:N
F = p(i)*X(pairs(i,1))^e(i,1)*X(pairs(i,2))^e(i,2);
end
  3 Commenti
Thorsten
Thorsten il 29 Giu 2015

Ok, then it is straightforward

F = p(1)*X(2)^e(1,1)*X(3)^e(1,2) + ...
    p(2)*X(1)^e(2,1)*X(3)^e(2,2) + ...
    p(3)*X(2)^e(3,1)*X(3)^e(3,2);  
Walter Roberson
Walter Roberson il 29 Giu 2015
The variables are strings, Thorsten, and the number of terms (the p values) is variable.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by