Minimalist
Minimalist

Reputation: 975

Initialize Variables in a Function

In a SCRIPT, I'm able to initialize variables which is displayed as empty variables in the workspace:

mass = [];
speed = [];
velocity = [];

BUT when I place these same initialize variables in a FUNCTION, MATLAB does not recognize them and does not store them in the workspace.

function myvariables()

    mass = [];
    speed = [];
    velocity = [];

How can I execute initialize variables in a function?

Upvotes: 0

Views: 1975

Answers (3)

thundertrick
thundertrick

Reputation: 1674

Using the output of a function if you really want to see these variables. For example:

    function [mass speed velocity] = initVariables()
        mass = [];
        speed = [];
        velocity = [];
    % ... 

Then you can pass them to other functions, which works as initialization. But your don't really need to do that.

Upvotes: 1

m_power
m_power

Reputation: 3204

Use breakpoints and F10 to run your function, you'll see that the variable are initiated in the function workspace (different than your base workspace).

Upvotes: 0

Eitan T
Eitan T

Reputation: 32930

MATLAB doesn't recognize them? Oh yes, it does!

It's just that those variables are stored in a different workspace (not the main workspace), which is bound to the scope of your function.

You can output their value to the command prompt to see that they do get initialized. For example, in your function after initializing mass = [] write mass to verify that this variable is indeed initialized like you want.

The official documentation has several nice articles related to your question that you might want to read:

  1. Base and Function Workspaces
  2. Share Data Between Workspaces

Upvotes: 5

Related Questions