user3518093
user3518093

Reputation: 69

Declare Variable outside function

I am not sure why i can't do this. Why cant I declare a variable outside a function before it gets used. I get error an error saying temp is an undefined function or variable. I realize I can pass the variable into the function thisblah(temp) but that is not what I want to do. The below is a shortened/redacted version of what I want to do. I am trying to add functionality in an existing function and want to know how many times I enter. Also I know you can solve calling the temp variable persistent inside the function but I dont think that is right answer. Global doesnt work either.

temp = 0;

for i = 1:5
           thisblah
end


function thisblah
  temp = temp + 1;
  if temp(3)
    fprintf('yes a three');
  end
  fprintf('temp is %d, temp);
end

Upvotes: 0

Views: 1209

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4757

Global Approach:

As the comments above have suggested an example of a global approach (making temp a global variable) is below. Also, temp will not have an 3rd index, temp(3) by simply incrementing it. To check when the function has been entered 3 times you can check if temp == 3.

global temp;
temp = 0;

for i = 1: 5
    thisblah
end

function thisblah

global temp;
  temp = temp + 1;
  if temp == 3
    fprintf('yes a three\n');
  end
  fprintf('temp is %d\n', temp);

end

Persistent Approach:

If you make the function in a separate .m file you can simply call clear thisblah instead of clear functions which needs to be there to clear the persistent variable after the script is done being run or before the script is re-run.

clc;
for i = 1: 5
    thisblah
end

clear functions;

function thisblah
persistent temp

if isempty(temp)
        temp = 0;
end

temp = temp + 1;
  
  if temp == 3
    fprintf('yes a three\n');
  end
  fprintf('temp is %d\n', temp);

end

Also, the syntax of line needs changing from:

fprintf('temp is %d, temp);

to

fprintf('temp is %d\n', temp);

Ran using MATLAB R2019b

Upvotes: 1

Related Questions