Persistent variables when passing a matrix through a function

조회 수: 5 (최근 30일)
Levko
Levko 2023년 1월 21일
편집: John D'Errico 2023년 1월 21일
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
Torsten
Torsten 2023년 1월 21일
편집: Torsten 2023년 1월 21일
Why don't you simply pass y_(n-1) to "myFunction" together with x_n ?

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2023년 1월 21일
편집: John D'Errico 2023년 1월 21일
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.

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by