Persistent variables when passing a matrix through a function

1 view (last 30 days)
I have an matrix x that I am passing through a custom function.
x = 0:1:10;
y = myFunction(x);
The key part is that myFunction() depends on the value of myFunction().
What I did was declare a persistent variable within myFunction that updates during each iteration, and retains the value of . The problem is that (I think) myFunction acts independantly on each and does not retain the persistent variable when acting on a matrix.
The problem is fixed if insead of passing the matrix x, I create a for loop and iterate through it for each . In that case, the persistent variable updates as expected.
Is there a way to force MatLab to "sequentially" go through the array?
  1 Comment
Torsten
Torsten on 21 Jan 2023
Edited: Torsten on 21 Jan 2023
Why don't you simply pass y_(n-1) to "myFunction" together with x_n ?

Sign in to comment.

Answers (1)

John D'Errico
John D'Errico on 21 Jan 2023
Edited: John D'Errico on 21 Jan 2023
Yes, there is. By passing the elements of x in sequentially to myfunction. But then, you already learned that.
Or, since myfunction is written by you, you can just have an internal loop there, which remembers the last pass through the loop. I don't see the problem.
Trying to use persistent variables here is the wrong way to solve it, since you want to solve the problem as if you were calling the function multiple sequential times. But since you want to call it only once, that can never work. And worse, using persistent variables and then multiple function calls will probably be slower anyway, since this just costs additional function call overhead for every call to your function.
Just use a loop. Either an internal loop inside myfunction, or an external loop around your function. If you want better help, then you would need to tell people what myfunction does. Show the code. Then we might be able to help you better, by possibly showing you how to write the code to work on only one call, and to do so efficiently.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!