Info

This question is closed. Reopen it to edit or answer.

# how can I improve the logic of this code

1 view (last 30 days)
summyia qamar on 8 Jan 2018
Closed: MATLAB Answer Bot on 20 Aug 2021
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?

### Answers (2)

Walter Roberson on 8 Jan 2018
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.
##### 0 CommentsShowHide -1 older comments

Image Analyst on 8 Jan 2018
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!