How can I write a mathematical function in Matlab?

조회 수: 11 (최근 30일)
ND
ND 2015년 6월 25일
댓글: ND 2015년 7월 1일
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

채택된 답변

Walter Roberson
Walter Roberson 2015년 6월 25일
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
Walter Roberson
Walter Roberson 2015년 6월 30일
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 2015년 7월 1일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Thorsten
Thorsten 2015년 6월 29일
편집: Thorsten 2015년 6월 29일
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
Thorsten
Thorsten 2015년 6월 29일

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 2015년 6월 29일
The variables are strings, Thorsten, and the number of terms (the p values) is variable.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by