0

What I want to be able to do is to take the elements of a vertical vector from a matrix and assign them to variables. I have provided a simple example below to show what I want to happen.

for k = 1 : 20
    a(:,k) = [k k+2];
end

[b, c] = a(:, 4)

so in this case

b = 4
c = 6

I know this can be done with this method

values = a(:, 4);
b = values(1);
c = values(2);

But I wanted to know if the vector values can be assigned without having to do all that mainly to make things easier to manage. Any advice welcome!

1
  • MATLAB doesn’t have automatic unpacking of arrays, but I don’t see what is hard about b=a(1,4); c=a(2,4);. Any other method you can come up with is going to be more verbose and less clear. Commented Dec 23, 2020 at 23:40

1 Answer 1

0

Dynamic creation of variable is not recommended

The closest you can try, if it makes sense, is to use a struct; in this case it is possible to dynamically define its fields.

Starting with your code, you can create a struct named var_str with two fields, b and c as follows:

for k = 1 : 20
    a(:,k) = [k k+2];
end

% Select the column
col_idx=4;
% Define the names of the variablesa as the names og the struct fields
list_of_vars={'b','c'}
% Assign the valurs to the struct fields
for var_idx=1:length(list_of_vars)
   var_str.(list_of_vars{var_idx})=a(var_idx,col_idx)
end

You can access the data in the fields and the field names by using the functions:

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, yeah i've decided i wanted to add more different data to what i'm working on and so will be adding more data classes to the existing structures that i've set up to handle it, thanks for the advice!

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.