0

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.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
Judy
  • 1,533
  • 9
  • 27
  • 41

3 Answers3

6

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.

Phonon
  • 12,549
  • 13
  • 64
  • 114
  • 1
    if you decide to go with structs, this answer might also be helpful: http://stackoverflow.com/questions/4166438/how-do-i-define-a-structure-in-matlab/4169216#4169216 – Amro Sep 30 '11 at 23:39
2

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.

Nzbuu
  • 5,241
  • 1
  • 29
  • 51
1

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,:)
Amro
  • 123,847
  • 25
  • 243
  • 454