Search code examples
matlabfor-loopplotmatlab-figure

Simulation with plotting within for loop - making faster discretization


It must be quiet simple thing, but I'm lost with it. dt/tsym describes rate of change o my values - tsym simulates full hour in seconds and dt one second which in my case is basically one iteration. My objective is to make simulation less accurate but faster - where dt can be 2 second or even 10 seconds. My dt is a part of equations.

tsym=3600; %[s]
x=zeros(0,tsym)
y=zeros(0,tsym);
h=zeros(0,tsym); 
dt=0;

 for dt=1:tsym

Q1=v1*cww*k1*t1+v1*cwp*pwp*t1;
Q2=(dV*cww*k1*t1+dV*cwp*pwp*t1)*(dt/tsym); %out
Q3=(dV*cww*k3*t3+dV*cwp*pwp*t3)*(dt/tsym); %in
Q1=Q1-Q2+Q3; %po jednym cyklu

W1=(v1-dV*(dt/tsym))*k1+dV*(dt/tsym)*k3; %kg
k1=(W1/v1); % kg/m3
%parameters
t1=Q1/(v1*cwp*pwp+cww*W1);
fi1=(k1*1000*(1+0.00366*t1)/(4.88624*(10^(t1*A/(t1+B)))))*100;
%PLOTS
x(dt)=dt;
y(dt)=t1;
h(dt)=fi1;
drawnow

hold on
subplot(2,1,1);
plot(x-1,y);
grid on
title('Temperature');
xlabel('sec');
ylabel('t1 [C]');
subplot(2,1,2);
grid on
plot(x-1,h);
title('Humidity');
xlabel('sec');
ylabel('\Phi [%]');
   end

With this code I'm receiving a correct plot but it takes quiet a while. In order to receive it faster i should make sampling time which is dt longer, but if i change for loop step size it just creates another lines for each value of dt every iteration. Should i create separate variables or loops to create faster plots? Correct plot but takes long to simulate.
Incorrect plot


Solution

  • I assume you want to see the plot animate. Otherwise you could just do all of the plotting after the loop completes and it would be much faster.

    However, if you do want to see it animate then do the following. Move initial plotting code outside of the loop. Only update your YData of the line handle inside of the loop. This removes a bunch of the plotting overhead.

    I also initialized y and h to NaN so the line was invisible until the parameter is filled.

    tsym=3600; %[s]
    dt=0;
    
    % Initialize vars outside of loop
    x = 1:tsym;
    y = nan(size(x));
    h = nan(size(x));
    
    % Initialize plot outside of loop
    a(1) = subplot(2,1,1);
    lH(1) = plot(a(1),x-1,y);
    title(a(1),'Temperature');
    xlabel(a(1),'sec');
    ylabel(a(1),'t1 [C]');
    hold(a(1),'on')
    grid(a(1),'on')
    
    a(2) = subplot(2,1,2);
    lH(2) = plot(a(2),x-1,h);
    title(a(2),'Humidity');
    xlabel(a(2),'sec');
    ylabel(a(2),'\Phi [%]');
    hold(a(2),'on')
    grid(a(2),'on')
    
    for dt=1:tsym
    
        % xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        % REMOVED YOUR CODE I COULDN'T TEST
        % Simulate with random number
        % xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        y(dt)=rand(1,1); %t1;
        h(dt)=rand(1,1); %fi1;
    
        %Update Plot
        lH(1).YData = y;
        lH(2).YData = h;
        drawnow
    end