# Extracting a range from a cell array.

10 views (last 30 days)
Erwin Werkhoven on 1 Jan 2022
Edited: Stephen23 on 3 Jan 2022
Hi,
Consider this example:
a = ["a", "b", "c", "d", "e"]
b = a(3:end)
x = {"a", "b", "c", "d", "e"}
y = x(3:end)
z = x{3:end}
It gives the following output:
a =
1×5 string array
"a" "b" "c" "d" "e"
b =
1×3 string array
"c" "d" "e"
x =
1×5 cell array
{["a"]} {["b"]} {["c"]} {["d"]} {["e"]}
y =
1×3 cell array
{["c"]} {["d"]} {["e"]}
z =
"c"
I'd expect that z = x{3:end} would give the same 1x3 string array as b. Why does it only extract element "c"?
And how can I get result b (the 1x3 string array) from x?
##### 2 CommentsShowHide 1 older comment
Erwin Werkhoven on 1 Jan 2022
Ok thanks for the explanation!

DGM on 1 Jan 2022
Edited: DGM on 1 Jan 2022
x = {"a", "b", "c", "d", "e"}
x = 1×5 cell array
{["a"]} {["b"]} {["c"]} {["d"]} {["e"]}
z = horzcat(x{3:end})
z = 1×3 string array
"c" "d" "e"
% or just
z = [x{3:end}]
z = 1×3 string array
"c" "d" "e"
To clarify, the expression x{3:end} has three outputs. When only a single output is requested, you'll only get the first one of the three.
Stephen23 on 3 Jan 2022
Erwin Werkhoven: with MATLAB basically everything is an array:
Even scalar numbers are arrays:
X = 3
X is an array which has size 1x1(x1x1...). Square brackets always concatenate things together: this is exactly the same for every single array type (e.g. numeric, char, string, cell, struct). So this:
X = [1,2,3]
really just concatenates three 1x1 arrays into a 1x3 array.
The only thing you need to pay attention to, is what you are concatenating together. In both of your examples the separate string arrays and character arrays respectively are concatenated into larger string and character arrays. Absolutely no difference whatsoever, the square brackets always concatenate.
This is a 1x1 numeric array: 2
This is a 1x1 numeric array: 3
If we concatenate them together horizontally, we will get a 1x2 numeric array.
This is a 1x1 character array: 'a'
This is a 1x1 character array: 'x'
If we concatenate them together horizontally, we will get a 1x2 numeric array.
This is a 1x1 string array: "x"
This is a 1x1 string array: "hello world".
If we concatenate them together horizontally, we will get a 1x2 string array.
etc. etc for every other array type.
Note that the number of characters (i.e. content) does NOT determine the size of a string array (this also applies to other container array types too, e.g. cell arrays and structure arrays). Do not mix up the size of the content of a container array with the size of the container array itself:
The documentation clearly states that string is a container type.