What is 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 that this is essentially the same thing?

+5
source share
5 answers

{} for cells. [] for arrays / matrices.

+11
source

[] is the operator associated with the array. An array can be of any type - an array of numbers, an array of char (string), an array of structures, or an array of cells. All elements of the array must be of the same type!

Example: [1,2,3,4]

{} is a type. Imagine that you want to put elements of various types into an array - a number and a string. This is possible with a trick - first put each element in the container {} , and then create an array with these containers - an array of cells.

Example: [{1},{'Hallo'}] with the abbreviation {1, 'Hallo'}

There is no need to put objects of the same type (doubles) in an array of cells, as in your example.

+8
source

Not. They are not at all the same. The only aspect that is one and the same is the resulting form.

An array (which you build with []) is something you can use for linear algebra. One number in each item.

 A = [1 2 3;4 5 6;7 8 9]; [3 5 7]*A*[2 3 5]' ans = 915 

A cell array is a common container that will contain any object, any matlab variable completely in each cell. Thus, we can create an array of cells consisting of elements of any shape and size.

 C = {'The' 'quick' 'brown' 'fox' 'jumps' 'over' 'the' 'lazy' 'dog'}; 

C is an array of cells with 9 elements in it. We can put any class of variables into it.

 C = {'asfghhrstyjtysj', 1:5, magic(4), sqrt(-1)} C = 'asfghhrstyjtysj' [1x5 double] [4x4 double] [0 + 1i] 

We could even create an array of cells, where each cell contains only one scalar number. But it would not make real sense, since we cannot perform arithmetic operations using arrays of cells.

+4
source

If you relate to object-oriented programming, cells {} are like objects and [] for arrays

+1
source

Elements of different data types that fall inside {} become cells or cell elements of a data type. Elements inside [] retain their data type and constitute an array of this data type. A 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 
+1
source

Source: https://habr.com/ru/post/1307168/


All Articles