Matlab doesn't save the new variable to the Workspace?
조회 수: 4 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Image Analyst
2018년 11월 27일
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);
댓글 수: 3
Image Analyst
2018년 11월 27일
WHY are you now having the Inlet function call itself??? Why did you do that? I did not tell you to do that. I told you to change the function definition, and the way you call it in your main calling routine (your script above your function). Do what I said and it should work.
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!