0

I've looked at a few other questions but I couldn't come up with an answer, I'm relatively new to MatLab (but not programming) so I apologize if it's a duplicate.

I'm sure the title isn't very clear so here's an example:

I have an array, say name = ['Jack';'Jill'];. The elements in this array reference other arrays, such as:

Jack.income = 31000;
Jack.car = 1;
Jill.income = 55000;
Jill.car = 0;

Now, I would like to use name to pull data from the other arrays, such as:

data = name(1).income, which should return 31000, or data = name(2).car, which should return 0.

Any help on this would be greatly appreciated.

Thank you very much,

Eric

1 Answer 1

1

You'd be better off using an array of structs (or making your own person object perhaps):

people(1).name = 'Jack';
people(1).income = 31000;
people(1).car = 1;
people(2).name = 'Jill';
people(2).income = 55000;
people(2).car = 0;

Now you can generate a list of names like this (see cell arrays and comma separated lists):

names = {people.name};

which you can convert into an index like this (see logical indexing and ismember):

ind = ismember(names, 'Jack');

and then finally extract someone's income:

people(ind).income
Sign up to request clarification or add additional context in comments.

1 Comment

Agreed. By the way, structed array is the fastest container datatype (in the sense of often element extraction/recording). Neither tables, not cell arrays are good.

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.