MATLAB: A{:} vs A(:) when A is a cell array - matlab

If A is a cell array in MATLAB, I wanted to learn the difference between A{:} and A(:) and where I should them.

As you can read in official documentation, the former refers to indexing a set of cells in the array (actually, all of them) and the latter refers to indexing a set of underlying values in the array (again, all of them).
Cell arrays are nothing but homogenic arrays whose elements are all cells, and cells have an underlying value that can be of any type. Round parentheses simply access the cells (the wrapping objects of the underlying values), while curly braces access the elements wrapped by the cells themselves (the underlying values).
Let's make a quick example. Round parentheses will return a cell array, since a single colon operator (:) is used and the matrix is flattened:
A = {1 2; 3 4};
A(:)
ans =
4×1 cell array
[1]
[3]
[2]
[4]
Curly braces, on the opposite, will return the underlying value of each cell (doubles):
A = {1 2; 3 4};
A{:}
ans =
1
ans =
3
ans =
2
ans =
4
In this second case, if you want an array to be returned, you have to write the selector as follows:
[A{:}]
ans =
1 3 2 4

Related

How to append an empty array to a cell array

How do you append an empty array to a (non-empty) cell array?
For example, starting with
c={[1],[2]}
desire
c={[1],[2],[]}
Concatenation would remove the empty array whether it is double, char or cell.
In addition to #Adriaan's answer, note that you can also do this with concatenation, if you are careful.
>> c = {1, 2}
c =
1x2 cell array
{[1]} {[2]}
>> [c, {[]}]
ans =
1x3 cell array
{[1]} {[2]} {0x0 double}
The trick here is to concatenate explicitly with another cell (your question suggests you tried [c, []] which does indeed do nothing at all, whereas [c, 1] automatically converts the raw 1 into {1} before operating).
(Also, while pre-allocation is definitely preferred where possible, in recent versions of MATLAB, the penalty for growing arrays dynamically is much less severe than it used to be).
You can just append it by using end+1:
c={[1],[2]}
c =
[1] [2]
c{end+1} = [] % end+1 "appends"
c =
[1] [2] []
MATLAB note: appending is usually used as a way to grow an array in size within a loop, which is not recommended in MATLAB. Instead, use pre-allocation to initially apply the final size whenever possible.

List declaration with/without bracket in matlab

For example, Why are 1:5 and [1:5] the same in matlab?
What is the reason behind this convention?
The reason for the convention is hard to tell without asking the creators of MATLAB, but here's a little insight. I apologies if this is a bit messy.
If you don't bother reading it all, here's the executive summary:
: is used to create regularly spaced vectors, while square brackets are used for concatenating.
First, you should know that even scalars are considered to be matrices in MATLAB. Scalars are simply 1x1 matrices, or to be more specific: 1x1x1x1x......1. There are in theory infinite amount of trailing singleton dimensions.
1 == [1] == [[[1]]]
Also:
a = 1;
a(1,1,1,:,:,1) %% Messy indexing showing how you can index a matrix using more dimensions than it appears to have.
ans =
1
The documentation says:
The colon operator is used to create regularly spaced vectors (and subscript arrays, and specify for iterations).
As scalars can be created without brackets, there's no reason you should need brackets around a clearly and unambiguously defined operator.
Brackets [] on the other hand creates vectors or matrices by concatenating values and vectors. From the documentation:
Square brackets are used in array construction and concatenation, and also in declaring and capturing values returned by a function.
Therefore, you can basically put brackets around anything you want. The same example as with the scalar above:
1:4 == [1:4] == [[[1:4]]]
Or around cells (doesn't change anything):
a = {3,1:4,'Hello, World!'}
a =
[3] [1x4 double] 'Hello, World!'
b = [a]
b =
[3] [1x4 double] 'Hello, World!'
Concatenating strings:
str1 = 'Hello';
str2 = ', World!';
str = [str1 str2]
str =
Hello, World!
Concatenating vectors:
[1:4, 6:8, 10]
ans =
1 2 3 4 6 7 8 10
If you had to put brackets around the 1:4 part, this would be (also works, but much more cumbersome):
[[1:4], [6:8], 10]
ans =
1 2 3 4 6 7 8 10
A possible reason for the convention:
It would be inconsistent if you needed brackets around 1:3.
Unrelated: For anyone used to other programming languages, brackets inside brackets often means you "go up" one dimension. Therefore, this might be confusing to some.
Well in a way they are and are not the same , In MATLAB every thing is a matrix , even
a = 5
is 1x1 matrix , for 1-D matrix or vector they will perform the same operation
when you write
>> x=1:3
ans =
1 2 3
MATLAB consider the matrix as one dimensional , like for instance in the example below it consider only the last row of the declaration
>> x=1:3;2:4
ans =
2 3 4
but when you specify brackets it can be an nxm dimensional matrix
>> x=[1:3;1:3]
x =
1 2 3
1 2 3

Best way to extend unique so that it can work on a cell array of scalars

The Matlab function unique doesn't work on a cell array of scalars, e.g.
>> unique([1 2 3 1])
ans =
1 2 3
>> unique({1 2 3 1})
Error using cell/unique (line 85)
Input A must be a cell array of strings.
What can I do to modify the unique function so that it can work on a cell array of scalars? i.e. I would like
>> unique({1 2 3 1})
ans =
[1] [2] [3]
I recommend to use either strings in a cell or doubles in a vector. Many functions like unique only apply to cell arrays of strings, not to any other cells.
unique({'1' '2' '3' '1'})
To convert the cell, use
cellfun(#num2str,{1,2,3,1},'uni',false)

Assign a row to cell array in Matlab?

I am trying to do this as with matrices:
>> line_params{1,:} = {numberPatterns{i}, lw, iw};
The right hand side of this assignment has too few values to satisfy the left hand side.
but getting error above.
Types are following:
>> class(line_params)
ans =
cell
>> size(line_params)
ans =
21 3
>> a={numberPatterns{i}, lw, iw};
>> class(a)
ans =
cell
>> size(a)
ans =
1 3
Change
line_params{1,:} = {numberPatterns{i}, lw, iw}
into
line_params(1,:) = {numberPatterns{i}, lw, iw}
(normal parenthesis).
If you use curly braces ({}), you reference the individual elements. That is,
line_params{1,:}
will return a comma-separated list of elements in the cell line_params in its first row. You cannot assign a cell array (single item) to a comma-separated list (multiple items).
If you use parenthesis (()), you reference the cell entry, i.e., a cell array will be returned. And you can assign a cell array (single item) to another cell array (single item) -- provided they have the same dimensions of course.

What's the difference between {} and [] in MATLAB?

>> A={1 2;2 3}
A =
[1] [2]
[2] [3]
>> A=[1 2;2 3]
A =
1 2
2 3
It seems to me they are essentially the same thing?
{}'s are for cells. []'s are for arrays/matrices.
[] is an array-related operator. An array can be of any type - array of numbers, char array (string), struct array or cell array. All elements in an array must be of the same type!
Example: [1,2,3,4]
{} is a type. Imagine you want to put items of different type into an array - a number and a string. This is possible with a trick - first put each item into a container {} and then make an array with these containers - cell array.
Example: [{1},{'Hallo'}] with shorthand notation {1, 'Hallo'}
It is unnecessary to put objects of the same type (doubles) into a cell array like in your example.
No. They are not at all the same thing. The only aspect that is the same is the resulting shape.
An array (that which you build with []) is something you can use to do linear algebra. One number in each element.
A = [1 2 3;4 5 6;7 8 9];
[3 5 7]*A*[2 3 5]'
ans =
915
A cell array is a general container, that will hold any object, any matlab variable entirely in each cell. Thus we can create a cell array composed of elements of any shape and size.
C = {'The' 'quick' 'brown' 'fox' 'jumps' 'over' 'the' 'lazy' 'dog'};
C is a cell array with 9 elements in it. We can put any class of variable in there.
C = {'asfghhrstyjtysj', 1:5, magic(4), sqrt(-1)}
C =
'asfghhrstyjtysj' [1x5 double] [4x4 double] [0 + 1i]
We could even create a cell array where each cell contains only a single scalar number. But there would be no real point in doing so, as we cannot do arithmetic operations using cell arrays.
If you relate it to object oriented programming,
cells {} are like objects and [] is for arrays
Elements of different data types which get inside {} become cells or elements of data type cell. Elements inside [] retain their data type and make an array of that data type. Few examples below:
p = ['my', 'string'];
q = [int8(1), int8(2), int8(3)];
r = [0.11, 0.22, 0.33];
s = {'my', 'string'};
t = {1,2,3};
u = {0.11, 0.22, 0.33};
v = {int8(1), int8(2), int8(3)};
>> whos
Name Size Bytes Class Attributes
p 1x8 16 char
q 1x3 3 int8
r 1x3 24 double
s 1x2 240 cell
t 1x3 360 cell
u 1x3 360 cell
v 1x3 339 cell