Info

此问题已关闭。 请重新打开它进行编辑或回答。

how can I improve the logic of this code

1 次查看(过去 30 天)
Im trying to build a relation between supply demand and price using 3 equations. the code I've generated is given below
clear all;
clc;
T=100;
P=zeros(1,T);
D=zeros(1,T);
R=zeros(1,T);
P(1)=10; %Initial Price
D(1)=10; %Initial Demend
R(1)=5; % Initial Resource available
K=100; %Maximum demand
M=10; %maximum resource
N=50; %Max Price K/N=2; N/K=0.5; N/M=5; M/K=0.1
for t=2:T
D(t)=D(t-1)+((1-(P(t-1)/N))*(K/N));
P(t)=P(t-1)-((1-(D(t-1)/K))*(N/K))+((1-(R(t-1)/M))*(N/M));
R(t)=R(t-1)+((1-(D(t-1)/K)*(M/K)));
end
Xvals=1:T;
plot(Xvals,D,'b',Xvals,P,'r',Xvals,R,'g')
legend('Demand','Price','Resource')
when I run the code, the values get below zero. I want that whatever the results are but the values remain positive since neither of price nor demand nor resources can be negative. can anybody help me in improving these equations?

回答(2 个)

Walter Roberson
Walter Roberson 2018-1-8
You could do things like
D(t) = max(0, D(t-1)+((1-(P(t-1)/N))*(K/N)) );
This will substitute 0 if the value would have been negative.

Image Analyst
Image Analyst 2018-1-8
To clip values to 0, use this code after the loop but before you call plot.
% If arrays are below zero, then clip arrays to 0.
D = max(D, 0);
P = max(P, 0);
R = max(R, 0);

此问题已关闭。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by