It all depends on how you do the search, Matlab’s website is a good source of resources, although it is in English!
There are some ways to solve this problem, I will put the methods I would use
in the order I recommend using, but it depends a lot on what is being done. At the end I make a brief discussion of why your attempts do not work.
By far the easiest and safest way to use, so you avoid carrying variables that you do not need the other times calling the function. Just use the statement described in manual:
function [output_principal, meu_index] = foo(bar).
% Function here ...
%Em OUTRO lugar, Para chamar os resultados
[a,b]=foo(1)
%ou
a=foo(1)
%se quiser apenas o segundo valor
[~,b]=foo(1)
These two array types allow you to load different types of variables into just one matrix. In both cases you can use the struct
or cell
as input and output of functions, but each time using one of the values it is necessary to use the appropriate call. I will demonstrate only for the struct
, look at the manual to use the cell
.
function mystruct = foo(bar).
%dentro da funcão, quando já tiver os números que você quer
mystruct.index= index;
mystruct.output=output;
%Em OUTRO lugar, Para chamar os resultados
aaa=foo(1);
aaa =
struct with fields:
output: [2×2 double]
index: 1
%Claro que lá tem seus números e nomes!
%Para obter os valores, use o esquema similar a declaração
index=mystruct.index
output_principal=mystruct.output
In the latter case, and sometimes it is necessary, you can use declares it as global
. But this is something that can easily give problems, because the variable can be changed differently by different calls and it needs to be cleaned in the appropriate way (clear global variable
).
Should you really need use a global variable it needs to be declared global
in all functions.
Problems
inputCounter = Passo0(inputCounter);
This works, as long as it’s not the same function Passo0
that you’re calling initially. Using the variable name gives no difference in the output, because it only uses the values that are in that variable, not their names or references (I think it can be done via objects). Also, you are with different number of entries in Passo0
. That might be worked, but still every call of the function must be independent, thus leaving the value of the index without the reference you want.
CounterCheck = inputCounter.inputCounter;
If this is not declared as a structure and already initialized, this will give problems.
Do a=foo(a)
is not a problem, but it will take the value of a
, use in function foo
and overwrite this output (whatever it is) in a
. If the output is not a structure, it will not work in the syntax you have placed.
- Global
Probably, you should not have declared global everywhere, in this case Matlab does not have access to values in all functions.