# Matlab doesn't save the new variable to the Workspace?

6 views (last 30 days)
Danny Helwegen on 27 Nov 2018
Commented: Danny Helwegen on 27 Nov 2018
Hi, I have written a code that needs the number of rebounds of moving particles in a 2D box, now I needed to count the number of rebounds when the grid becomes bigger. This all works but my C isn't saved to the workspace, I need this to apply Curve Fitting. According to the Workspace C are all zeros.
This is my code:
N = 1000;
T = 1000;
L = 1:1:150;
l = 1:1:150;
C = zeros(size(L));
velocityx = randi([-1,1],N,1);
velocityy = randi([-1,1],N,1);
dt = 1;
Velocity = Inlet(N, velocityx, velocityy);
function Velocity = Inlet(N, velocityx, velocityy);
Velocity = [velocityx, velocityy];
N = 1000;
T = 1000;
L = 1:1:150;
l = 1:1:150;
C = zeros(size(L));
velocityx = randi([-1,1],N,1);
velocityy = randi([-1,1],N,1);
dt = 1;
for L = 1:1:150
x = randi([1,L],N,1);
y = randi([1,L],N,1);
for t = 1:1:T
for i=1:1:N
x(i) = x(i)+velocityx(i)*dt;
y(i) = y(i)+velocityy(i)*dt;
end
%Collisions
for i=1:1:N
%Collisions with the Y-axis bounds
if 0 == x(i) %Collision with chamber wall
C(L) = C(L)+1;
velocityx(i) = -velocityx(i)*dt;
velocityy(i) = randi([-1,1]);
end
if (L+1) == x(i) %Collision with chamber wall
C(L) = C(L)+1;
velocityx(i) = -velocityx(i)*dt;
velocityy(i) = randi([-1,1]);
end
% Collisions with the X-axis bounds
if 0 == y(i) %Collision with chamber wall
C(L) = C(L)+1;
velocityy(i) = -velocityy(i)*dt;
velocityx(i) = randi([-1,1]);
end
if (L+1) == y(i) %Collision with chamber wall
C(L) = C(L)+1;
velocityy(i) = -velocityy(i)*dt;
velocityx(i) = randi([-1,1]);
end
end
end
Velocity = [velocityx, velocityy];
idx = Velocity(:,1) == 0;
vec = [1; -1];
Velocity(idx,2) = vec(randi(numel(vec),nnz(idx),1));
end
plot(C);
corrcoef(C,l);
end
This is a C according to my code:
Columns 145 through 151
8654 8623 8644 8555 8484 8422 8365
And this is what C is according to the workspace:
0 0 0 0 0 0 0 0 0 0 0 0
How can I now make sure that the C in the workspace is also the C that my function gives?

Image Analyst on 27 Nov 2018
Each function or script in your code has its own private workspace. So the C in your script is different than the C in your function. If you want the C in your function to be passed out and replace the zeros that it started out with you need to declare it like this:
function [Velocity, C] = Inlet(N, velocityx, velocityy);
and call it like this:
[Velocity, C] = Inlet(N, velocityx, velocityy);
Danny Helwegen on 27 Nov 2018
Ah I see, I shouldn't put it in the function but above. My problem is solved now, he gives me now the result for C in the workspace.
Thank you