Post Reply  Post Thread 


MATLAB TIPS & TRICKS
Author Message
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #1
MATLAB TIPS & TRICKS

How to use cell arrays ({})

Basically, cell arrays are arrays of arrays ;-)
Here's an example:

� z={rand(2),rand(3);rand(4),rand(5)}
z =
[2x2 double] [3x3 double]
[4x4 double] [5x5 double]
� z{1,1}
ans =
0.6813 0.8318
0.3795 0.5028


Arrays may be of different sizes and types. Especially useful are cell arrays to store text data:

� txt={'This is first string';'This is second'}
txt =
'This is first string'
'This is second'


Note that in order to store the same two strings in a normal array, you'd have to pad them to the same length!

Another very useful feature is that z{:} is always equivalent to comma separated list: "z{1},z{2},...". So you can use the cell array to pass parameters to a function...

� attrib={'p-','color',[.5 .1 .7],'linewidth',3};
� plot(x,y,attrib{:})
� legend(txt{:}); % in fact, you can omit {:}
here

... or from a function:

� grid={[],[]}; contours={[],[]};
� [grid{:}]=meshgrid(0:10,0:10);
� grid{3}=grid{1}.*grid{2};
� [contours{:}]=contour(grid{:});
� clabel(contours{:})


Besides, you can easily convert a cell array to a normal one:

� z={[1,2],[3,4,5]}
z =
[1x2 double] [1x3 double]
� [z{:}] % again, equivalent to [z{1},z{2}] !
ans =
1 2 3 4 5


As you can see, it can be a very powerfull tool

07-29-2008 07:00 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
Post Reply  Post Thread 

View a Printable Version
Send this Thread to a Friend
Subscribe to this Thread | Add Thread to Favorites

Forum Jump: