1

Let's say, I have a variable, arrayName = 'array1'. Then, I wish to declare an array whose name is the value of the variable arrayName, i.e. 'array1'.

I don't think

arrayName = []

will work.

I am using MATLAB, but I think this question is a generic question.

2 Answers 2

4

One other option is to use ASSIGNIN, which makes it easier to specify the value. In your case, you might replace EVAL with

assignin('caller', arrayName, magic(4));
Sign up to request clarification or add additional context in comments.

Comments

3

Using eval you could do it as follows:

   arrayName = 'array1';

   if isvarname(arrayName)
       eval([arrayName, ' = [];']); 
   end

2 Comments

This works like a charm! Thanks a lot! One follow-up question: The if is just to ensure that arrayName is a variable right? If I know this for sure, can I leave it out?
@FarticlePilter Yes you can. isvarname checks if string can be a variable, e.g. it does not start with 1.

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.