Cell Arrays
1. Data Types (Review)
2. General Concept
3. Creating Cell Arrays
4. Augmenting Cell Arrays
5. Referencing Cell Arrays1. The entire cell/ The content of the cell
6. Special case
1
1. Data Types
Recall the workspace frame in MATLAB. Currently, 4 types of data have been seen. They are called:
This chapter teaches how to operate more specifically with the cell array
2
2. General Concepts
Still an array Still has to be rectangular BUT:
Each cell is more of a CONTAINER rather than one single element
3
This is just a nice picture. It still has to be rectangular. :o) But the container itself can be empty, have different data types, different content inside…
General Concepts, cont.
“Cells” are a structure used by MATLAB. They…
• can contain any mix of data-type: string, integer, float, another cell array…
• are used with many library functions to provide a “use anything” format
• use a slightly different syntax for creating, deleting, and referencing
4
“Cell Arrays” are exactly that – arrays of “cells”
Quick Vocabulary
Let's be clear:
"Parentheses" ( )
"Square Brackets" [ ]
"Curly Braces" { }
5
3. Creating Cell Arrays
Experiment in the command window:
6
Curly braces – not parentheses, not brackets!
Creating Cell Arrays, cont.
Experiment in the command window:
7
Note how numbers in cells are displayed with brackets
Creating Cell Arrays, cont.
Experiment in the command window:
8
But strings are not!
Creating Cell Arrays, cont.
Plot them using cellplot()!
9
FYI: It is just a representation. J is in the first box, o in the second, e in the third.
4. Augmenting Cell Arrays
How about adding on a new cell to the array? For example, add on the string 'def'.
10
{ } are not used to augment. They are strictly used to create new cell-arrays from scratch.
The curly braces indicate ‘def’ is added OUTSIDE of the cell-array C – i.e. C is a completely new cell-array!
Augmenting Cell Arrays, cont.
11NOT what we wanted...
Augmenting Cell Arrays, cont.
Augment the same as with normal arrays: use brackets
12
4b. Augmenting vertically
Can a 2D cell-array exist? Of course. Still use the ; operator to add a new row.
13
5. Referencing Cell Arrays There are 2 ways to reference a cell array, depending on
the task:
1. Get the entire container as a whole. (Do not open the doors to see the content) to move the container to extract/copy/replace the container to delete the container
2. Get the content inside the container. (Open the doors, and use the content) To change its content To display/print its content
14
Referencing Cell Arrays, cont.
1. Get the entire container as a whole. (Do not open the doors to see the content)
2. Get the content inside the container. (Open the doors, and use the content)
15
Parentheses ()
Curly Braces {}
>>>T-H-E MOST IMPORTANT SLIDE<<<
Assume C starts with:
%option1: refer to & delete the 2nd container
Referencing Cell Arrays, cont.
16
Assume C starts with:
%option1: refer to & delete the 2nd container
%option2: refer to & delete the content of the 2nd container
Referencing Cell Arrays, cont.
17
This is particularly important if you wish to use the values mathematically (equations, … )
For example:
Using the variable X mathematically creates issues...
Referencing Cell Arrays, cont.
18
The content (numerical value 2) is still inside the container, as indicated per the brackets.
To use this variable X mathematically creates an error
After all, this is what MATLAB tries to execute:
result = 2* + 5
Referencing Cell Arrays, cont.
19
?
Referencing Cell Arrays, cont.
Recall to use curly braces to access the CONTENT.
20
Use curly braces {}. Notice the lack of [] around the result.
Referencing Cell Arrays, cont.
To conclude, also use curly braces to replace elements.
21
Initial data-base (name, age, weight)
Fix the name
6. Special Case
What if there is an array within a cell?
22
1) max?2) last score?
6. Special Case
What if there is an array within a cell?
"Max of the content of container 2". Use { }.
23
1) max?
Special Case, cont.
The following requires patient imagination skills, but it works and makes sense!
24
Simply: "Reference to the 3rd element in the CONTENT of the 2nd container"
Simply: "Reference to the last element in the CONTENT of the 2nd container"
Special Case, cont.
Most would prefer storing the content in a intermediate variable, then referencing that variable.
25
Wrapping Up
Cells arrays are ‘cargo-ships’ Rectangular arrays allowing storage of different data-
types into 1 variable.
Cell-arrays use all types of braces:Creating/hard-coding: Braces { }Referencing to content: Braces { }
Augmenting: Brackets [ ]
Referencing to container: Parentheses ()
26
Most likely to be used often!
Dialog Boxes(Using Cell arrays)
1. Example Project
2. Example GUI
3. inputdlg()
4. help
27
Real life#1 - tables A previous year’s project calculated the friction of a stunt man on a
surface. The user had to choose two surfaces (the clothing the stuntman wore, and the material he/she was sliding to), and whether it was a dry or wet surface. All was contained in 1 variable:
28
Material 1 Material 2
leather leather
leather concrete
leather wood
leather clay
leather weed
Friction
dry wet
0.9 0.1
0.7 0.4
0.8 0.3
0.6 0.2
0.61 0.52
strings.. Numerical data..
Strings..
A BIG CELL-ARRAY!
data={…};
Dialog Boxes: overview
Dialog boxes are “popup windows” that allows another means to communicate with the user.
There are dialog boxes to collect input:
inputdlg(), listdlg(), menu(), questdlg()
And there are dialog boxes to produce output:
msgbox(), warndlg()
30
Dialog Boxes: timing
Timing wise: Modal (“waiting”) – they prevent the program from continuing
until the box is closed Non-modal (“non-waiting”) – the program continues execution
while the box remains open
31
Dialog Boxes: timing
Timing wise: Modal (“waiting”) – they prevent the program from continuing
until the box is closed Non-modal (“non-waiting”) – the program continues execution
while the box remains open
Examples: Input boxes are generally modal – the program waits for input
before continuing. This is not changeable.
Output boxes default to non-modal (“non-waiting”) but can be made modal.
32
Dialog Boxes: One Example Prompt the user for the coefficients to the quadratic
equation, then solve for the roots. Requirements: Use a GUI to prompt the values, specifically
inputdlg()
33
…
inputdlg(), overview Collects information from the user
inputdlg() – much like the input() function, except… It is presented in a GUI form (Graphical User Interface) There can be multiple prompts and multiple values provided by
the user.
34
inputdlg(), overview Collects information from the user
inputdlg() – much like the input() function, except… It is presented in a GUI form (Graphical User Interface) There can be multiple prompts and multiple values provided by
the user.
ALL user-provided information is returned as strings in a cell array!
That’s why learning about cell-arrays is important!
35
inputdlg(), syntax
Arguments A cell array of strings: This is the set of prompts for the user. For
example:
prompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'}
36
inputdlg(), syntax
Arguments A cell array of strings: This is the set of prompts for the user. For
example:
prompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'}
Return Values One (1) cell-array of strings: What the user provided in the boxes
37
inputdlg(), syntax
Arguments A cell array of strings: This is the set of prompts for the user. For
example:
prompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'}
Return Values one (1) cell-array of strings: What the user provided in the boxes
Full Exampleprompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'};
coeffs = inputdlg(prompts);
38
Cell-array, indicated by the curly braces.
inputdlg(), output
41
When collecting numbers, use str2double() to convert the cell-array (cargo-ship) into a numerical vector:
coeffs = str2double(coeffs);
Application: Quadratic Formula
42
clearclcprompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'};a = 0; b = 2; c = 3; %wrong values to make loop run once % No invalid inputs, or imaginary rootswhile (a==0 || (b*b - 4*a*c) < 0)
% Collect the coeff’s from the user coeffs = inputdlg(prompts); coeffs = str2double(coeffs); a = coeffs(1); b = coeffs(2); c = coeffs(3); end
%calculate rootsroots(1) = (-b + sqrt(b*b-4*a*c))/(2*a)roots(2) = (-b - sqrt(b*b-4*a*c))/(2*a)
Application: Quadratic Formula
43
clearclcprompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'};a = 0; b = 2; c = 3; %wrong values to make loop run once % No invalid inputs, or imaginary rootswhile (a==0 || (b*b - 4*a*c) < 0)
% Collect the coeff’s from the user coeffs = inputdlg(prompts); coeffs = str2double(coeffs); a = coeffs(1); b = coeffs(2); c = coeffs(3); end
%calculate rootsroots(1) = (-b + sqrt(b*b-4*a*c))/(2*a)roots(2) = (-b - sqrt(b*b-4*a*c))/(2*a)
Extract the values from the vector: Must this be done, or should it be done for convenience?
Application: Quadratic Formula
44
clearclcprompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'};a = 0; b = 2; c = 3; %wrong values to make loop run once % No invalid inputs, or imaginary rootswhile (coeffs(1)==0 || (coeffs(2)^2-4*coeffs(1)*coeffs(3)<0) % Collect the coeff’s from the user coeffs = inputdlg(prompts);end
%calculate rootsroots(1) = (-coeffs(2) + sqrt(coeffs(2)^2- ...
4*coeffs(1)*coeffs(3))/(2*coeffs(1))
roots(2) = (-coeffs(2) - sqrt(coeffs(2)^2- ...4*coeffs(1)*coeffs(3))/(2*coeffs(1))
Really..
Application: Quadratic Formula
45
clearclcprompts={'Coeff "a":', 'Coeff "b":', 'Coeff "c":'};a = 0; b = 2; c = 3; %wrong values to make loop run once % No invalid inputs, or imaginary rootswhile (a==0 || (b*b - 4*a*c) < 0)
% Collect the coeff’s from the user coeffs = inputdlg(prompts); coeffs = str2double(coeffs); a = coeffs(1); b = coeffs(2); c = coeffs(3); end
%calculate rootsroots(1) = (-b + sqrt(b*b-4*a*c))/(2*a)roots(2) = (-b - sqrt(b*b-4*a*c))/(2*a)
Since the prompts do not change each time it loops, avoid having this line within the loop. Time & effort consuming for Matlab.
Dialog Boxes, help
MATLAB figures (various types of windows: dialog boxes, plots, etc) have many, many options available to them: position, size, resizable, etc.
If you want to do more than fundamental dialog boxes, study the MATLAB help documentation.
46
F1 = Help
47
F1 = Help
Possibility of having up to 5 arguments!!!
Wrapping Up
GUI stands for Graphical User Interface Dialog boxes are part of GUI Most use cell-arrays as arguments and as return values Non-Modal boxes (output) disappear from the screen.
(Like a pop-up window that closes ASAP..)
Modal boxes stay on the screen (input) inputdlg() was tremendously explained in these slides Use F1/help to learn all the others. BY NOW, ALL THE
VOCABULARY USED IN THE HELP HAS BEEN TAUGHT. YOU CAN FLY BY YOURSELF! menu(), listdlg()…
1.Reminder of Symbols
2.Dialog Boxes
3.listdlg()
4.msgbox()
5.questdlg()
6.menu()
Dialog BoxesApplications of Cell-Arrays
49
1. Reminders on Symbols
Creating/hard-coding: Braces { } Referencing to content: Braces { }
Augmenting: Brackets [ ]
Referencing to container: Parentheses ()
Most likely to be used!
50
2. Dialog Boxes
Dialog boxes are “popup windows” that allows us another means to communicate with the user.
Some dialog boxes to collect input:
inputdlg(), listdlg(), menu(), questdlg()
And some to produce output:
msgbox(), warndlg()
99% of the time, the command deals with cell arrays, either as arguments, as return-values, or both!
5252
3. listdlg()
listdlg() – Create and open list-selection dialog box
Major Advantage:
User does not have
to type anything
Less spelling
errors!
53
>>doc listdlg() <enter>
This function returns 2 return-values.
54
[Selection,ok] = listdlg('ListString',S)
Selection is a vector of indices of the selected strings
(in single selection mode, its length is 1). Selection is [] when ok is 0. ok is 1 if you click the OK button, or 0 if you click the Cancel button or close the dialog box. Double-clicking on an item or pressing Return when multiple items are selected has the same effect as clicking the OK button. The dialog box has a Select all button (when in multiple selection mode) that enables you to select all list items.
55
listdlg() return-values
What will the first return-value be after this executes?
a. {'Primary Booster','Secondary Boosters'}
b. [1 3]
c. {1, 3}
d. None of the above
56
[Selection,ok] = listdlg('ListString',S)
Selection is a vector of indices of the selected strings
(in single selection mode, its length is 1). Selection is [] when ok is 0. ok is 1 if you click the OK button, or 0 if you click the Cancel button or close the dialog box. Double-clicking on an item or pressing Return when multiple items are selected has the same effect as clicking the OK button. The dialog box has a Select all button (when in multiple selection mode) that enables you to select all list items.
If user hits cancel or closes the dialog box, an empty-vector is returned, AND ok is set equal to 0.
This means the second return-value can be used to see what the user did!
57
What did user do?
Did user hit ok? Did user hit cancel?
Either way: Had s/he selected anything anyway?
If user did click ok, then ok will be true, which equals 1. If user did not click ok, then ok will be false, which equals 0.
58
Inputs are in parameter/value pairs (i.e. they go 2 by 2):
Parameter goes 1st, value of the parameter goes 2nd.
[Selection,ok] = listdlg('ListString',S)
The actual string:
59
myList is a CELL ARRAY of string: { }
Why cell arrays?
The length of each selection varies widely, and an regular-array would not be rectangular.
Experiment in the command window!
60
Experiment in the command window!
What button did the user hit?
a. The 'ok' button
b. The 'cancel' button
c. The [x] that closes the window
d. Either b or c
e. None of the above
61
A second parameter
Though additional arguments are not necessary, you may choose to add them AS A PAIR. For example:
62
2nd PAIR of inputs.
63
The Select All button is gone.
2nd PAIR of inputs.
64
What did the user select?
a. It cannot be determined
b. __________________________
3.a. Full Example
Create a software that estimates the time an aircraft takes to travel a certain distance.
Aircrafts possible, with their average speeds are:
1) Cessna 150, 198 kmph
2) Boeing 787, 950 kmph
3) Concorde, 2147 kmph
4) Cessna 421, 444 kmph
66
Algorithm
%prompt user for type of airplane (error?)
%prompt user for distance to travel (error?)
%calculate/display
Presented is the evolution from: Option1: use input() and if. (week 2,3.4) Option2: use input() and vectors. (week 10) Option3: using listdlg(), vectors and cell-arrays.
67
#1. input(), if and while
%prompt user for type of airplane
type = input('Enter the type of airplane: \n1 – cessna 150\n 2-Boeing 787\n3-Concorde\n4-Cessna 421\n Enter now: ');
%prompt user for distance to travel
distance = input('Enter the distance (km): ');
%calculate/display
if type == 1 %cessna 150
travelTime = distance/198;
fprintf('With this plane, it will take %.2fhrs.\n', travelTime);
elseif….
68
Add while loops to trap errors.
#2. input(), vectors, while
%prompt user for type of airplane
type = input('Enter the type of airplane: \n1 – cessna 150\n 2-Boeing 787\n3-Concorde\n4-Cessna 421\n Enter now: ');
%prompt user for distance to travel
distance = input('Enter the distance (km): ');
%data base of speeds
speeds = [198, 950, 2147, 444];
%calculate/display
travelTime = distance/speeds(type);
fprintf('With this plane, it will take %.2fhrs.\n', travelTime);
69
Add while loops to trap errors.
Reference the correct value in the vector, using the index.
#3. listdlg(), arrays, while%prompt user for type of airplane
myPlanes = {'Cessna 150', 'Boeing 787', 'Concorde', 'Cessna 421'};
type = listdlg('ListString', myPlanes,'selectionmode', 'single');
%prompt user for distance to travel
distance = inputdlg('Enter the distance (km): ');
%data base of speeds
speeds = [198, 950, 2147, 444];
%calculate/display
travelTime = distance/speeds(type);
fprintf('With this plane, it will take %.2fhrs.\n', travelTime);
70
Add while loop to trap errors, and convert to number
Reference the correct value in the vector, using the index.
#3. Output
Note: once a software starts with dialog boxes, it should end with dialog boxes…
>> not in the command window.. 71
4. msgbox()
A little improvement:
%calculate/display
travelTime = distance/speeds(type);
resultString = sprintf('With this plane, it will take %.2fhrs.\n', travelTime);
msgbox(resultString)
72
4. msgbox()
A little improvement:
%calculate/display
travelTime = distance/speeds(type);
resultString = sprintf('With a %s, it will take %.2fhrs.\n', ??????, travelTime);
msgbox(resultString)
73
Task: Replace "this plane" by the actual name!
4. msgbox()
%prompt user for type of airplane
myPlanes = {'Cessna 150', 'Boeing 787', 'Concorde', 'Cessna 421'};
type = listdlg('ListString', myPlanes,'selectionmode', 'single');
Remember: this is the index (i.e. location) of the string selected.
This is the cell-array of all the names.
To reference the name selected using the index selected:
planeSelected = myPlanes{type};
74REFERENCE the CONTENT, using curly braces.
4. msgbox()
A little improvement:
%calculate/display
travelTime = distance/speeds(type);
resultString = sprintf('With a %s, it will take %.2fhrs.\n', myPlanes{type}, travelTime);
msgbox(resultString)
75
Make the software error proof!%prompt user for type of airplane
myPlanes = {'Cessna 150', 'Boeing 787', 'Concorde', 'Cessna 421'};
[type ok] = listdlg('ListString', myPlanes,'selectionmode', 'single');
%if user hits ok, continue
if ok==1
%prompt user for distance to travel
distance = inputdlg('Enter the distance (km): ');
%code as before
else
%user hit cancel of closed box..
%do other stuff
end76
Done with that example.
Note how much a software has improved since your first knowledge of week2, and yet not too many lines of code were required.
Hopefully, you're pausing and coding this in parallel.
Use them in the final project if you want. Make sure to error-proof accordingly.
77
5. questdlg()
Typical call:
button = questdlg('qstring','title','str1','str2',
'str3','default')
qstring = Question to ask the user title = Title for dialog box str1 = String to show on Button #1 str2 = String to show on Button #2 str3 = String to show on Button #3 default = String that is the default button button = string on the button that was clicked
Caution: Maximum of 3 buttons.
78
5. Quick experiment
button = string on the button that was clicked
79
6. menu() – vertical menu
Typical call:button = menu('qstring','bt1','bt2',……,'btn')
qstring = question to ask user bt1 = String to show on Button #1 bt2 = String to show on Button #2
Can have as many options as desired. There is no default answer. Return value: Button number clicked (not the string)
80
What's next???
Yes, we are done with cell-arrays and dialog boxes.. So what's next? Files!
83
Wrapping Up
Dialog boxes are user friendly but time taking Dialog boxes should not be used when the software is
not meant to be sold. Lots of clicking vs. entering data in the command window. Choose carefully.
We saw: inputdlg() listdlg() msgbox() questdlg() menu()
NEVER learn the syntax by heart. Practice it enough, then use the doc to remind yourself quickly!
84
Top Related