how to plot a function with vectorized variables

7 次查看(过去 30 天)
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 个评论
Guillaume
Guillaume 2017-8-15
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 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by