Judy
Judy

Reputation: 1553

How to create a vector of cell arrays

I want to store all the contents like name and marks for 30 students. I am keeping the information of name and marks together in a cell array. But to compare 2 students I need to store the cell arrays in a vector of 30 elements so that I can access later.

Upvotes: 0

Views: 5714

Answers (3)

Amro
Amro

Reputation: 124553

Say you had the following:

names = {'Andrew'; 'Betty'; 'Charles'}
marks = [90; 92; 88]

I suspect you tried this:

>> C = {names marks}
C = 
    {3x1 cell}    [3x1 double]

Basically it creates a 1x2 cellarray (vector). You can access the values for a student as: C{1}{3} and C{2}(3).

A more convenient form is to create a 3x2 cellarray (matrix):

>> C = [names num2cell(marks)]
C = 
'Andrew'     [90]
'Betty'      [92]
'Charles'    [88]

which is easier to manipulate. For example if you want to extract the first and last students for comparison:

C([1 end],:)

You can do things like sort by grade or by name:

[~,idx] = sort(marks);
C(idx,:)

Upvotes: 1

Nzbuu
Nzbuu

Reputation: 5251

Is it a 2D cell array that you want:

students = cell(30, 2);
students{1,1} = 'Andrew';
students{1,2} = 90;
% or
students(2,:) = {'Becky' 92};
% etc

Or a cell array of cell arrays?

students = cell(30, 1);
students{1}{1} = 'Andrew';
students{1}{2} = 90;
% or
students{2} = {'Becky' 92};
% etc

In any case, I strongly recommend using an array of structures, as suggested by @Phonon.

Alternatively, you can use an array of objects. Check out the object-oriented programming information in the MATLAB help.

Upvotes: 2

Phonon
Phonon

Reputation: 12727

I would recommend using an array of structs. For example

students(1) = struct('name','Andrew', 'mark',90);
students(2) = struct('name','Betty', 'mark',92);
students(3) = struct('name','Charles', 'mark',88);

You can then simply refer to them by indexing as student(n). You can also get and set their specific fields such as someName = student(2).name or student(1).mark = 98.

Upvotes: 6

Related Questions