1

I am not a very hardcore coder in MATLAB, i have learned every thing from youtube and books. This might be a very simple question but i do not know what search for answer.

In MATLAB i am trying to do something like this.

>>[a,b,c] = [1,2,3]

and i want output like this.

>> a = 1 
b = 2
c = 3

So Bsically question is that : - User will define the matrix of variables([a,b,c]) in staring of code and during process of the code similar matrix will be displayed and as input a matrix will be asked([1,2,3]). I dont know how do this without writing a loop code in which i will take every single variable from variable matrix and save the value in that variable by eval function.

well above written code is wrong and i know, i can do this with "for" loop and "eval" function.

but problem is that no. of variables(a,b,c) will never be constant and i want know if there exist any in built function or method in MATLAB which will work better than a for loop.

As i told earlier i don't know what to search for such a problem and either this is a very common question. Either way i will be happy if you can at least tell me what to search or redirect me to a related question.

Please do write if you want any more information or for any correction.

Thank you.

2 Answers2

1

This is somehow known as "tuple unpacking" (at least it's what I would search in python!). I could find this thread which explains that you could do this in Octave (I checked and it works in Matlab also). You have to transform the vector into a cell array before:

values = num2cell([1,2,3])
[a,b,c] = values{:}
Community
  • 1
  • 1
Emilien
  • 2,385
  • 16
  • 24
1

The deal function can do this for a fixed number of inputs:

[A,B,C]=deal(1,2,3)

If you don't know how many inputs you will get beforehand, you have to do some fooling around. This is what I've come up with:

V=[1,2,3,4,5,6,7]
if length(V)>1
    for i=1:length(V)
        S{i}=['A' num2str(i)];
        G{i}=['V(' num2str(i) ')'];
    end
    T=[S{1} ','];
    R=[G{1} ','];
    for i=2:length(V)-1
        T=[T S{i} ','];
        R=[R G{i} ','];
    end
    T=[T S{length(V)}];
    R=[R G{length(V)}];
    eval(['[' T ']=deal(' R ')'])
else
    A1=V
end

But then dealing with A1, ... , An when you don't know how many there are will be a pain!

David
  • 8,449
  • 1
  • 22
  • 32