'How to write a square function in Matlab?
I am trying to write a code in Matlab to generate a square function as shown in the attached figure. When I tried coding this in Matlab, I got a trapezoid function instead of a perfect square. Please note that the time at tinjb, tinje, and tend is not an exact multiple of the time step (dt). For reference, I have also included a screenshot of the time and mdotf values that are expected.
i = 2;
tsim = 0;
flag1 = 0;
flag2 = 0;
mdotL(1) = 0;
tout(1) = 0;
mliqtot = 0;
while tsim < tend
dt = 0.7;
tsim = tsim + dt;
if tsim < tinjb
mdotl = 0;
elseif tsim >= tinjb && flag1 == 0
dt = tsim - tinjb;
tsim = tinjb;
mdotl = 0;
flag1 = 1;
elseif tsim == tinjb
mdotl = 1;
elseif tsim > tinjb && tsim < tinje
mdotl = 1;
elseif tsim >= tinje && flag2 == 0
dt = tsim - tinje;
tsim = tinje;
mdotl = 1;
flag2 = 1;
elseif tsim == tinje
mdotl = 0;
else
mdotl = 0;
end
mliqtot = mliqtot + mdotl * dt;
tout(i, 1) = tsim;
mdotL(i, 1) = mdotl;
i = i + 1;
tsim = tsim + dt;
end
Please help me get this right. This is for my research.
Solution 1:[1]
The plot of your code looks like a triangle because of the large timesteps. I think this does everything you explained in your description.
clc; clear all; close all;
tStart = 0; %tsim
tEnd = 5; %tend
tStep = 0.7; %dt
a = 1; %tinjb
b = 2; %tinje
x = tStart:tStep:tEnd;
y = rectangularPulse(a,b,x); %mdotf
subplot(2,1,1); plot(x,y);
syms tSym;
subplot(2,1,2); fplot(rectangularPulse(a,b,tSym), [0 5]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anouk |