how to plot a function with vectorized variables

I need help to plot function (code pasted below) which takes a vector input. The code is given below. The input variable x is a real valued vector of length 30 e.g x= rand(30,1);. I would appreciate any help in this regard>
function profit = simpObjFunc(x)
a = [0.003573; 0.011283; 0.005800; 0.008649];
b = [1.435859; 1.306349; 1.510772; 1.794831];
Dm =[2.7231; 2.8185; 2.9834; 1.5008];
Sm = [0.8197; 0.7724; 0.8237; 0.7719 ];
Earning = 30* (6 - sum (a./(x.* b - a* 30)));
S = 0.003 + (x.*(Sm - 0.003));
D = 30* (a.*Dm./b );
z = D + S;
Expense=0.04.* sum(z) + 0.3;
profit = (Earning - Expense);
end

댓글 수: 1

The function shown will only work with
  • a scalar x, it will return a scalar
  • a 4x1 vector, it will return a scalar
  • since R2016b, any size row vector (1xn), it will return a row vector of the same size.
It will error out on any other size input, including a 30x1 column vector
Since the behaviour is not consistent, it clearly is a bug that it works in all 3 cases above. Adding basic input checks to the function and basic documentation headers would greatly improve the code.

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

 채택된 답변

Image Analyst
Image Analyst 2017년 8월 15일
편집: Image Analyst 2017년 8월 15일
x can't be 30 long because you're doing x.* b and you can't do an element by element multiplication of a 30 element long vector by a 4 element long vector.
Other than that, I don't know what you want to plot. What do you want along the x and y axes? Which variables are to be plotted against each other?
Perhaps try this:
x = linspace(0, 1, 100);
for k = 1 : length(x)
profit(k) = simpObjFunc(x(k))
end
plot(x, profit, 'b-', 'LineWidth', 2);
grid on;
fontSize = 20;
xlabel('x', 'FontSize', fontSize);
ylabel('profit', 'FontSize', fontSize);

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Annotations에 대해 자세히 알아보기

질문:

2017년 8월 15일

댓글:

2017년 8월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by