Convert cell array with sub cells into numeric array - matlab

Assume I have A that is a 64x1 cell array.
Each of the 64 cells contains another cell with a string (which is a number, i.e. 11)
A{1, 1}{1, 1} = ’11’ (char)
A{2, 1}{1, 1} = ’13’ (char)
How can I create a numeric array such as
A = [11,13,…]
The cell2mat function seems to work only on “first level” cell array:
cell2mat does not support cell arrays containing cell arrays or objects.

You can use cellfun to convert the contents of each individual cell in A to doubles.
A{1, 1}{1, 1} = '11';
A{2, 1}{1, 1} = '13';
A_array = cellfun(#(a) str2double(a), A)
Breakdown of the function: #(a) passes the contents of each cell of A to the variable a, which can be converted to doubles using str2double(a).

It's quite simple, however you need split it to two steps. Let's assume we have simple 1x4 string array:
A= {'11','13','15','17'};
To convert it you need store the content in temporary variable S, then use sscanf to generate final result:
S = sprintf('%s ', A{:});
Result = sscanf(S, '%f')
The only problem is that it will be column vector. If you need it in a row, you can just transpose(Results).

I'm not sure I entirely understand your question. If I've got it right, you're talking about a cell array like asd below
asd=cell(61,1);
for ii=1:64
asd{ii}={['test',num2str(ii)]}
end
If I understand your goal correctly, I think the following does it somewhat neatly
A=char([asd{:}])
Then if you want to convert the strings to numbers (which wouldn't work for my test, but might for your strings), just use str2num on this new vector

Transform A into a comma-separated list of cells, then horizontally concatenate these cells and finally apply str2double;
A = str2double([A{:}]);

Related

Function for comparing two cell arrays

I have a cell array (2000*10) with each cell containing a string such as '25:20:55'.
I want to write a function that accepts 10 inputs (say '25:02:33', '58:69:88', '25:54:96', '48:58:36', '58:54:88' and so on) and looks for a match in each column corresponding to input value for that particular column (i.e. the first input data corresponds to 1st column, 2nd to 2nd column of the stored data and so on.
How can I write a function for the above comparison?
Assuming the cell array contains strings, you can find matches using strcmp:
input = {'25:02:33', '58:69:88', '25:54:96', '48:58:36', '58:54:88'};
match_idx = strcmp(repmat(input, size(cell_data,1),1), cell_data);
If you only want to know if there are matches in the respective columns at all and do not care about the line index of the match, you can do
match = any(match_idx,1);
Use ismember
ismember(your_var, your_cell);
e.g.
c = {'a', 'b', 'c', 'd'};
ismember('b', c)
ans =
1
ismember('q', c)
ans =
0
In your case, something like could work
function arr = myfun(inputvec, inputmat)
for i=1:length(inputvec) %// where inputvec is the cell-vector with the strings you want to search for
arr(i) = ismember(inputvec{i}, inputmat{:,i});
end

Matlab: How do you seperate text in existing cell

I'm a bit new to the matlab world, and I'm running into an issue that I'm sure has an easy solution.
I've imported some data from a text file and parsed out the headers, which resulted in a 1x35 cell called Data. In each cell (for example Data{1,1,1}) is data that looks like:
'600000 -947.772827 -107.045776 -70.818062'
'600001 -920.431396 -86.098122 -56.485119'
'600002 -878.332886 -88.673630 -85.249130'
'600003 -851.637695 -68.546539 -96.691711'
'600004 -834.707642 -28.951260 -73.218872'
'600005 -783.431580 40.657402 24.242268'
The problem is, each line is contained in a single column. I'd like to parse it out so that I have 4 columns instead of one.
I tried parsing out the Data cell even further using:
textscan(Data{1,1,1}, '%u%f10%f10%f10', 1)
But it resulted in the following error:
Error using textscan
First input must be of type double or string.
Can I use textscan this way, or do I need to use some other method to break out the text?
With textscan, you can only specify a single string or a single number. With your input, I suspect it is a 6 x 1 cell array of strings. As such, you have no choice but to iterate over each cell and convert each cell array contents with textscan Also, get rid of the %10 spacing as it's actually screwing up where you're parsing out the string. Also, set the identifier to identify the first number you see to double (%f) as opposed to unsigned integer (%u) to allow for easier conversion.
Therefore, do something like this:
>> Data{1,1,1} = {'600000 -947.772827 -107.045776 -70.818062'
'600001 -920.431396 -86.098122 -56.485119'
'600002 -878.332886 -88.673630 -85.249130'
'600003 -851.637695 -68.546539 -96.691711'
'600004 -834.707642 -28.951260 -73.218872'
'600005 -783.431580 40.657402 24.242268'};
>> format long g;
>> vals = cell2mat(cellfun(#(x) cell2mat(textscan(x, '%f%f%f%f', 1)), Data{1,1,1}, 'uni', 0))
vals =
Columns 1 through 3
600000 -947.772827 -107.045776
600001 -920.431396 -86.098122
600002 -878.332886 -88.67363
600003 -851.637695 -68.546539
600004 -834.707642 -28.95126
600005 -783.43158 40.657402
Column 4
-70.818062
-56.485119
-85.24913
-96.691711
-73.218872
24.242268
That statement vals = ... is quite a mouthful, but easy to explain. Start with this statement:
cell2mat(textscan(x, '%f%f%f%f', 1))
For a given cell x in Data{1,1,1}, we want to parse out four numbers for each string that is stored in x. textscan will place these numbers as individual cell elements into a cell array. We want to convert each element into a numeric array, and so cell2mat is required for us to do so.
In order to operate over all of the elements in Data{1,1,1}, we need to use cellfun to allow us to do so:
cellfun(#(x) cell2mat(textscan(x, '%f%f%f%f', 1)), Data{1,1,1}, 'uni', 0)
The first input is a function that operates on each cell stored in Data{1,1,1} (the second input). We are basically telling cellfun that we want to operate on each cell in the cell array stored in Data{1,1,1} in the way I talked about before. This function has input parameter x, which is one cell from Data{1,1,1}. Now, the uni flag is set to 0 because the output of cellfun will not be a single number, but an array of numbers - one array per line that you have in your cell array. The output of this stage would be a 6 element cell array where each location is a 4 element numeric array. To finish it off, we call cell2mat on this output to finally convert our text into a 2D matrix and therefore:
vals = cell2mat(cellfun(#(x) cell2mat(textscan(x, '%f%f%f%f', 1)), Data{1,1,1}, 'uni', 0))
format long g allows for better display formatting so we can see both the dominant number as well as the floating point numbers neatly.

Scanning data from cell array and removing based on file extensions

I have a cell array that is a list of file names. I transposed them because I find that easier to work with. Now I am attempting to go through each line in each cell and remove the lines based on their file extension. Eventually, I want to use this list as file names to import data from. This is how I transpose the list
for i = 1:numel(F);
a = F(1,i);
b{i} = [a{:}'];
end;
The code I am using to try and read the data in each cell keeps giving me the error input must be of type double or string. Any ideas?
for i = 1:numel(b);
for k = 1:numel(b{1,i});
b(cellfun(textscan(b{1,i}(k,1),'%s.lbl',numel(b)),b))=[];
end;
end;
Thanks in advance.
EDIT: This is for MATLAB. Should have been clear on that. Thanks Brian.
EDIT2: whos for F is
Name Size Bytes Class Attributes
b 1x11 13986188 cell
while for a is
Name Size Bytes Class Attributes
a 1x1 118408 cell
From your description I am not certain how your F array looks, but assuming
F = {'file1.ext1', 'file2.ext2', 'file3.ext2', 'file2.ext1'};
you could remove all files ending with .ext2 like this:
F = F(cellfun('isempty', regexpi(F, '\.ext2$')));
regexpi, which operates on each element in the cell array, returns [] for all files not matching the expression. The cellfun call converts the cell array to a logical array with false at positions corresponding to files ending with .ext2and true for all others. The resulting array may be used as a logical index to F that returns the files that should be kept.
You're using cellfun wrong. It's signature is [A1,...,Am] = cellfun(func,C1,...,Cn). It takes a function as first argument, but you're passing it the result of textscan, which is a cell array of the matching strings. The second argument is a cell array as it should be, but it doesn't make sense to call it over and over in a loop. `cellfun´'s job is to write the loop for you when you want to do the same thing to every cell in a cell array.
Instead of parsing the filename yourself with textscan, I suggest you use fileparts
Since you're already looping over the cell array in transpose-step, it might make sense to do the filtering there. It might look something like this:
for i = 1:numel(F);
a = F(1,i);
[~,~,ext] = fileparts(a{:});
if strcmpi(ext, '.lbl')
b{i} = [a{:}'];
end
end;

Compare two cell array elements in matlab

I am trying to compare two cell arrays, 1x160 (a) and 80x1(b). My cell arrays consist of cells which have a number of strings inside. I wanna compare each string ans see if they are equal, then if they are equal, insert to new array, or insert 0 otherwise. I can't find any function for that. I tried 'isequal','strfind' and others. All of them give me next error message:
If any of the input arguments are cell arrays, the first must be a
cell array of strings and the second must be a character array.
Here is my code!
function [inter]=Intersect2(a,b)
int=cell(0);
b2=[b;b];
for i=1:length(a)
if a{i,1}==b2{i,1}(1) ( or 'isequal','strfind')
int{i}=a{i};
else
int{i}=0;
end
end
There are many ways to compare character arrays, one of which is strcmp.
We'll use cellfun as well to avoid looping.
a = {'Dude', 'I', 'am', 'a', 'moose'};
b = {'Well', 'I', 'am', 'a', 'mouse'};
index = cellfun(#strcmp, a, b);
This will compare each element of a against the corresponding element in b, returning a logical array index that is 1 when the elements match and 0 when they do not.
Use this to assign matching values:
int = cell(1, length(a));
int(index) = a(index);
int =
[] 'I' 'am' 'a' []
You can extend this concept to find the set intersection if you wish.

Iterating through struct fieldnames in MATLAB

My question is easily summarized as: "Why does the following not work?"
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for i=1:numel(fields)
fields(i)
teststruct.(fields(i))
end
output:
ans = 'a'
??? Argument to dynamic structure reference must evaluate to a valid field name.
Especially since teststruct.('a') does work. And fields(i) prints out ans = 'a'.
I can't get my head around it.
You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:
for i = 1:numel(fields)
teststruct.(fields{i})
end
Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:
>> fields(1) % Get the first cell of the cell array
ans =
'a' % This is how the 1-element cell array is displayed
>> fields{1} % Get the contents of the first cell of the cell array
ans =
a % This is how the single character is displayed
Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.
Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for fn=fields'
fn
%# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
teststruct.(fn{1})
end
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.
>> signal
signal =
sin: {{1x1x25 cell} {1x1x25 cell}}
cos: {{1x1x25 cell} {1x1x25 cell}}
>> each(fieldnames(signal))
ans =
CellIterator with properties:
NumberOfIterations: 2.0000e+000
Usage:
for bridge = each(fieldnames(signal))
signal.(bridge) = rand(10);
end
I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.