script for a Function

조회 수: 3 (최근 30일)
Ahmed Elsadek
Ahmed Elsadek 2017년 4월 24일
댓글: Walter Roberson 2017년 4월 25일
Hello,
I have a function
y = 5 + 2*a - 3*b + 8*c + a*b
where a,b,c are variables such that: the values of
a = 4,6,8
b = 12,16,18
c = 1,3,9
How to write a script defining this function to used by an optimizing algorithm
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 4월 24일
Is the question which combination of values of the variables gives the lowest result?

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

답변 (1개)

Walter Roberson
Walter Roberson 2017년 4월 24일
Vectorize the expression of the equation.
Create grids of the permitted values using ndgrid or meshgrid .
Use the grid of values in the expression.
min() or max() to find the optimal result.
  댓글 수: 2
Ahmed Elsadek
Ahmed Elsadek 2017년 4월 24일
Thank you for feedback I just want to define the function to be used by another code. I want Matlab to know that I have a function of one dependent variable (y) and three independent ones (a,b,c) and each of a,b and c have certain values only (the ones that I mentioned in my original question) this script will be saved to be used by another code.
Walter Roberson
Walter Roberson 2017년 4월 25일
Supposing that y is a function handle that is not necessarily vectorized:
function [fval, best_a, best_b, best_c] = discrete_nonlin_optimize(y, a, b, c)
[A, B, C] = ndgrid(a, b, c);
values = arrayfun(y, A, B, C);
[fval, idx] = min(values);
best_a = A(idx);
best_b = B(idx);
best_c = C(idx);
In the special case that y is known to be vectorized,
function [fval, best_a, best_b, best_c] = discrete_optimize(y, a, b, c)
[A, B, C] = ndgrid(a, b, c);
values = y(A, B, C);
[fval, idx] = min(values);
best_a = A(idx);
best_b = B(idx);
best_c = C(idx);
This would be more efficient than the arrayfun version.
If your a, b, and c are quite large, you could run out of memory forming A, B, C. In that case you would have to change strategies, such as using ga() with integer constraints.

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

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by