If I want to pull an array from one file to another without defining global variables is there a command I can use?
Best Answer
It depends how the m-files are defined. If they are scripts (that is, they are not defined by the 'function' keyword at the top), the variables defined in them are automatically added to the "base" workspace, which includes all variables included in all other script files that are run, regardless of whether they are defined as global or not.
If the m-files are functions, you will need to pass out the useful variables as output variables from your function. This isstrongly preferred over using global variables.
Variables declared in a script exist in the base workspace. However, variables declared inside a function only exist in the function workspace. In other words, they are destroyed when the function returns and you shouldn't see them in the base workspace unless:
The variables are declared global (usingglobal is a bad practice, you should not declare global variables);
You are using the debugger and stopped during the execution of the function (in that case what you see is the function workspace);
The variables are outputted by the function into a script as in the following:
% Function file foo.m
function c = foo(a,b)
c = a + b;
end
% Script file script.m
clear all
close all
clc
c = foo(10, 12); % c is in the base workspace, because it was declared in a script
Could you copy and paste your function where you declaremog? If you want to learn more about functions and the scope of a variable, you can refer to theonline documentation on functions .
I am not sure if you can (easily) grab values from one workspace and pull them into the current function workspace... you might like to trydbup , which lets you change workspace while debugging. But variables only exist in one workspace, unless explicitly specified otherwise (e.g.global). It might be possible to do some major hackery usingassignin andevalin and the like, or perhaps even callingglobal, but this would not be beautiful...
You are correct that when using the debugger (on a function) the workspace shown in the IDE changes from the "base" workspace to that of the (normally hidden) function itself. All of the variables that you have defined within the function are shown there, including the ones that are inputs to the function. Thus the standard way to get variables from the base workspace into a function workspace is to call that function with those variables as input arguments, as the workspaces are kept quite separate.
Best Answer