0

I want to populate an empty array, and then access individual elements from within a function.

a = [];

for i=1:10
  a(i)=i;
end

function display_a(k)
  a = a(k);
  disp(a);
end

display_a(5)

Here I receive an error:

'a' undefined near line 8, column 7

Which means that a=a(k) within the function is not recognized as my array a. Any idea on how to pull this off?

I tried declaring a as a global variable. Apart from my understanding that declaring global variables is not a good practice, my function returns the whole array instead of just one, specified element.

Thank you in advance.

3
  • 1
    You need to pass the array into the function. Each function has its own scope, and does not see variables declared in other scores. Declare the function as function display_a(a,k). Commented Sep 30, 2022 at 19:52
  • 1
    Besides, avoid assignments like a = a(k) because after that the array a(:) becomes a scalar a (unless this is really what you want). Use an intermediate variable b=a(k); disp(b) or even directly disp(a(k)) Commented Sep 30, 2022 at 20:14
  • Thank you @CrisLuengo, that worked like a charm. In hindsight it's so obvious, I was aware of what the scope of the function is and tried to "solve" it by declaring a global variable, but I wasn't really able to connect all the dots myself - thanks! PierU, definitely, sorry about introducing the ambiguity into this example, I'd never do that in the actual working code. Commented Sep 30, 2022 at 20:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.