plotting function of multible variable

Hi. I am trying to plot the compression and de-compression of oil in a cylinder chamber with varying piston speed, but the script i am using now only does it for one constant speed. I am using a while loop to do numerical integration/derivation, and i want to use a for loop befrore the while loop where i can execute the while loop with different piston speeds.
With the script I am using now, matlab only returns the last values of my variables and i would like to "hold" them all to be plottet simultaneously.
The script I am using now:
hold on
for dx = 1:1:10;
Time=0;
EndTime=30e-3;
StepTime=1e-6;
ReportCounter=0;
ReportInterval=1;
Counter=ReportInterval;
while Time<EndTime
V_cyl_comp=V0_cyl- A_cyl*x_comp;
V_cyl_decomp=V0_cyl- A_cyl*x_decomp;
dV_cyl_comp= dx*A_cyl;
dV_cyl_decomp= dx*A_cyl;
dp_comp= beta./V_cyl_comp.*dV_cyl_comp;
dp_decomp= beta./V_cyl_decomp.*(-dV_cyl_decomp);
%numeric integration
x_comp=x_comp+dx*StepTime;
p_comp=p_comp+dp_comp*StepTime;
x_decomp=x_decomp+dx*StepTime;
p_decomp=p_decomp+dp_decomp*StepTime;
%Plot data
Time=Time+StepTime;
Counter=Counter+1;
TimePlot(Counter)=Time;
x_compPlot(Counter)=x_comp;
p_compPlot(Counter)=p_comp;
V_cyl__compPlot(Counter)=V_cyl_comp;
x_decompPlot(Counter)=x_decomp;
p_decompPlot(Counter)=p_decomp;
V_cyl_decompPlot(Counter)=V_cyl_decomp;
%Update new values to current values
end
end

1 Comment

Quick observation: You are using vectors to store the results of your computations, which means every iteration of the for-loop overrides the previous iteration results. If you want to keep results from each iteration, you should use matrices.

Sign in to comment.

Answers (2)

John D'Errico
John D'Errico on 12 Apr 2017
Edited: John D'Errico on 12 Apr 2017
Use a matrix to store your data, NOT vectors that you then over-write.
You can use cell arrays if you want, but as long as you create vectors of the same size with each iteration, storing them as columns (or rows) of an array will do fine.
PREALLOCATE the arrays to their final size in advance. Otherwise, your code will get very slow. You can use zeros to do the preallocation, although I tend to preallocate my arrays as NaNs, so using the function nan. That way it is more obvious what I've filled when I am testing the code.

Categories

Asked:

on 10 Apr 2017

Answered:

on 12 Apr 2017

Community Treasure Hunt

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

Start Hunting!