how to handle 'nested' arrays

35 views (last 30 days)
maho
maho on 9 Oct 2017
Edited: Cedric Wannaz on 11 Oct 2017
Hello, I am new to MatLab, and am having a problem with code like this:
x=["bar" "foobar" "food" "bard"];
y=regexp(x,'.*foo.*','match');
X is a string array, but the problem is y seems to be a cell array of string arrays- which I can't manipulate or use at all. So what I want to do is "simplify" y so that it is also a simple string array, by taking the first element of each element of the cell array. I.E., output should look like:
["" "foobar" "food" ""]
Any general references on how to handle and manipulate nested arrays of arrays would also be appreciated.

Accepted Answer

Guillaume
Guillaume on 9 Oct 2017
In this particular instance, the easiest way to solve your problem is to add the 'once' option to your regexp:
matches = regexp(x, '.*foo.*', 'match', 'once');
  6 Comments
Guillaume
Guillaume on 11 Oct 2017
which is best to use
That's a very easy question to answer: if you're on a version (R2016b or later) that support it and don't care about older versions, use string arrays. They're a lot more intuitive and powerful. strings didn't exist before R2016b so on earlier version char arrays where the only option.
You have to think of cell arrays as a container for any kind of things. The containers has cells where you put each things. You can look at the container itself, for example you can take the container that encompass rows 1:3 and columns 2:4. For that you use (), and you get another container:
container = cell(10, 20);
container_portion = container(1:3, 2:4); %container_portion is still a cell array
You can also looks at what's inside the container. That's when you use {}, you get whatever is inside each cell
container = cell(10, 20);
container{1, 5} %returns the content of cell(1,5)
You can ask for the content of several cells at once with {} and matlab returns a comma-separated list of the contents (see Cedric's Link), so if you do
matches{:}
you get a c-s-l of all the string arrays. You can pass that c-s-l to horzcat, which simply concatenate horizontally all its inputs, thus
horzcat(matches{:})
extracts the content of all the cells of the cell array and converts into a row vector of this content.

Sign in to comment.

More Answers (1)

jean claude
jean claude on 9 Oct 2017
Edited: jean claude on 9 Oct 2017
hi maho, i didn't understand what do you want exactly, but you can read here https://www.mathworks.com/help/matlab/ref/strsplit.html may be it helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!