Difference between these two cell array syntaxes?

54 Views Asked by At
ca = {'Airbus' 320; 'Boeing' 737};
cb = [{'Airbus'} 320; {'Boeing'} 737];

What is the difference between these two cell arrays, if any?

If I pass them to isequal, it returns 1 (true).

1

There are 1 best solutions below

0
Nick J On

I see you've tagged both Octave and MATLAB. Since it's possible there are differences between the two, here are the results from Octave 8.4.0. If someone doesn't provide a MATLAB output I may be able to add one here as a comparison later.

EDIT: I realize I misread your cb assignment as {} not []. I'll leave the old answer at the end of this updated one.

Looking at each one in Octave 8.4.0:

>>  ca = {'Airbus' 320; 'Boeing' 737}
ca =
{
  [1,1] = Airbus
  [2,1] = Boeing
  [1,2] = 320
  [2,2] = 737

>>  cb = [{'Airbus'} 320; {'Boeing'} 737] 
cb =
{
  [1,1] = Airbus
  [2,1] = Boeing
  [1,2] = 320
  [2,2] = 737
}

Both result in identical cell arrays because of how Octave interprets the concatenation operation with mixed cell and double inputs. As can be seen with cb above, it creates a cell array that is compositionally identical to the defined cell array ca. I don't see this behavior currently documented in the Octave documentation, but it is MATLAB compatible and appears in the Matlab online documentation.

This can be seen in a simpler example with two numbers, noting the order doesn't matter:

>> [{2},2 ]
ans =
{
  [1,1] = 2
  [1,2] = 2
}


>> [2, {2} ]
ans =
{
  [1,1] = 2
  [1,2] = 2
}```

(Previous mistaken answer comparing the string and cellstring.)

>>  ca = {'Airbus' 320; 'Boeing' 737}
ca =
{
  [1,1] = Airbus
  [2,1] = Boeing
  [1,2] = 320
  [2,2] = 737
}

>>  cb = {{'Airbus'} 320; {'Boeing'} 737} 
cb =
{
  [1,1] =
  {
    [1,1] = Airbus
  }

  [2,1] =
  {
    [1,1] = Boeing
  }

  [1,2] = 320
  [2,2] = 737
}

In the second case you are creating "cell strings" which are not the same as simple strings or character arrays (strings and char arrays are still the same thing in Octave, unlike MATLAB which implemented separate string objects.). Note that the cell contains cells containing the strings.

As for the isequal results, at least in octave the answer is no:

>> isequal (ca,cb)
ans = 0

similarly:

>> isequal('abc',{'abc'}) 
ans = 0

>> isequal({'abc'},{{'abc'}})  
ans = 0

Those objects just aren't the same. 9ctave looks at a string and the cell and flags them as not equal. If you were getting isequal to be true, please update your question with a copy/paste of exactly what code/commands you put in and what output the program gave you.