subindex into a cell array of strings - matlab

I have a 6 x 3 cell (called strat) where the first two columns contain text, the last column has either 1 or 2.
I want to take a subset of this cell array. Basically select only the rows where the last column has a 1 in it.
I tried the following,
ff = strat(strat(:, 3), 1:2) == 1;
The error message is,
Function 'subsindex' is not defined for values of class 'cell'.
How can I index into a cell array?

Cell arrays are accessed through braces {} instead of parentheses (). Then, as a 2nd subtlety, when pulling values out of a cell arrays, you need to gather them...for numerics you gather them into regular arrays using [] and for strings you gather them into a new cell array using {}. Confusing, eh?
ff = { strat{ [strat{:,3}]==1 , 1:2 } };
Gathering into cell arrays this way can often give the wrong shape when you're done. So, you might try something like this
ind = find([strat{:,3}]==1); %find the relevant indices
ff = {{strat{ind,1}; strat{ind,2}}'; %this will probably give you the right shape

Related

Printing progress in command window

I'd like to use fprintf to show code execution progress in the command window.
I've got a N x 1 array of structures, let's call it myStructure. Each element has the fields name and data. I'd like to print the name side by side with the number of data points, like such:
name1 number1
name2 number2
name3 number3
name4 number4
...
I can use repmat N times along with fprintf. The problem with that is that all the numbers have to come in between the names in a cell array C.
fprintf(repmat('%s\t%d',N,1),C{:})
I can use cellfun to get the names and number of datapoints.
names = {myStucture.name};
numpoints = cellfun(#numel,{myStructure.data});
However I'm not sure how to get this into a cell array with alternating elements for C to make the fprintf work.
Is there a way to do this? Is there a better way to get fprintf to behave as I desire?
You're very close. What I would do is change your cellfun call so that the output is a cell array instead of a numeric array. Use the 'UniformOutput' flag and set this to 0 or false.
When you're done, make a new cell array where both the name cell array and the size cell array are stacked on top of each other. You can then call fprintf once.
% Save the names in a cell array
A = {myStructure.name};
% Save the sizes in another cell array
B = cellfun(#numel, {myStructure.data}, 'UniformOutput', 0);
% Create a master cell array where the first row are the names
% and the second row are the sizes
out = [A; B];
% Print out the elements side-by-side
fprintf('%s\t%d\n', out{:});
The trick with the third line of code is that when you unroll the cell array using {:}, this creates a comma-separated list unrolled in column-major format, and so doing out{:} actually gives you:
A{1}, B{1}, A{2}, B{2}, ..., A{n}, B{n}
... which provides the interleaving you need. Therefore, providing this order into fprintf coincides with the format specifiers that are specified and thus gives you what you need. That's why it's important to stack the cell arrays so that each column gives the information you need.
Minor Note
Of course one should never forget that one of the easiest ways to tackle your problem is to just use a simple for loop. Even though for loops are considered bad practice, their performance has come a long way throughout MATLAB's evolution.
Simply put, just do this:
for ii = 1 : numel(myStructure)
fprintf('%s\t%d\n', myStructure(ii).name, numel(myStructure(ii).data));
end
The above code is arguably more readable in comparison to what we did above with cell arrays. You're accessing the structure directly rather than having to create intermediate variables for the purpose of calling fprintf once.
Example Run
Here's an example of this running. Using the data shown below:
clear myStructure;
myStructure(1).name = 'hello';
myStructure(1).data = rand(5,1);
myStructure(2).name = 'hi';
myStructure(2).data = zeros(3,3);
myStructure(3).name = 'huh';
myStructure(3).data = ones(6,4);
I get the following output after running the printing code:
hello 5
hi 9
huh 24
We can see that the sizes are correct as the first element in the structure is simply a random 5 element vector, the second element is a 3 x 3 = 9 zeroes matrix while the last element is a 6 x 4 = 24 ones matrix.

Round only numeric elements in cell array with different data types

I have a cell with different types of variables (double & strings), I want to round the numeric elements in the cell.
round function can work only with arrays and not with cells, so I'm trying to use cell2mat - but this function can't be used in case of different elements types in the cell.
Any idea how can I round the numeric elements in this cell? Of course I don't want to do loop over the cell elements.
As mentioned by Adriaan, this can be done with cellfun:
function testCell = q38476362
testCell = {'t','h',1.004,'s',[],'i',4.99,[],'a',[],'ce',10.8};
isnum = cellfun(#(x)~isempty(x) & isnumeric(x),testCell);
testCell(isnum) = num2cell(round([testCell{isnum}],0));
testCell =
't' 'h' [1] 's' [] 'i' [5] [] 'a' [] 'ce' [11]
If your cell array is random in terms of where the strings and where the doubles are, there's not much you can do besides loop/cellfun/bruteforce. If however, there is some periodicity (e.g. "a string is always followed by two double entries") you might be able to construct some indexing vector that would get you the values without having to iterate (explicitly or implicitly).
You want to take advantage of the str2double ability to convert non-numeric types into NaN.
Say you have a cell like:
A = {'1.999','3.1415','pie','??'}
B = round(str2double(A))
B =
2 3 NaN NaN

Writing the output of variable length cells into a single column cell array in MATLAB

I am trying to write the output from a variable length cell array to a single column cell array.
Eg:
I have
A a;b
B c
C b;c
D a;b;d
E e;g;h
F a;b
as the input file. I want to read all the entries in the second column into separate cells in a row and store the output as the following:
a
b
c
b
c
a
b
d.... and so on.
I tried
for m=1:size(txt)
c(:,m)=strsplit(txt{m},';');
end
However, I am unable to write the output into a column and getting the following error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
I understand that the dimensions of c should be more than that of size(txt) but I am not sure how to enter write the output from c into the first empty cell present in the column.
This is because you have declared c to be a matrix but you want it to be a single column. In addition, strsplit creates a cell array of results here each split string is placed in an element in the cell array. Also, this cell array is a row-wise cell array, meaning that you will get a cell array of dimensions 1 x N where N is the total number of strings resulting from the call the strsplit.
As such, what I would recommend you do is create a master cell array to store all of the strings as you iterate through each row, then concatenate and create one final cell array at the end.
Assuming the code you wrote up until this point is correct, do something like this:
c = cell(numel(txt), 1);
for m = 1 : numel(txt)
c{m} = strsplit(txt{m}, ';');
end
c = horzcat(c{:});
The first line creates a master cell array to store our string split characters per line of the text file. Next, for each line of the file, we split the string with the semicolon character as the delimiter and we place these split results into the right cell in the master array. Once this is finished, we use horzcat to place all of the characters into a single row of cells in the end. This creates a row of cell array elements though. Using horzcat is required as we are concatenating many row-wise cell arrays together into a single row. Trying to do this vertically will give you an error. Simply transpose the result if you want a column:
c = horzcat(c{:}).';

How to compare two cell elements in matlab?

I am using two cells for storing the targeted and the expected value of a neural network process in matlab. I have used two 1*1 cell array for storing the values respectively. And here is my code.
cinfo=cell(1,2)
cinfo(1,1)=iter(1,10)%value is retrieved from a dataset iter
cinfo(1,2)=iter(1,11)
amp1=cinfo(1,1);
amp2=cinfo(1,2);
if amp1 == amp2
message=sprintf('NOT DETECTED BY THE DISEASE');
uiwait(msgbox(message));
But when i run the above code, the get the following error :
??? Undefined function or method 'eq' for input arguments of type 'cell'.
Error in ==> comparison at line 38
if amp1 == amp2
How to solve this problem?
The problem is how you indexed things. A 1x1 cell array does not make a lot of sense, instead get the actual element in the single cell, by indexing with curly brackets:
amp1=cinfo{1,1}; # get the actual element from the cell array, and not just a
amp2=cinfo{1,2}; # 1x1 cell array by indexing with {}
if (amp1 == amp2)
## etc...
However, note that if amp1 and amp2 are not scalars the above will act weird. Instead, do
if (all (amp1 == amp2))
## etc...
Use isequal. That will work even if the cell's contents have different sizes.
Example:
cinfo=cell(1,2);
cinfo(1,1) = {1:10}; %// store vector of 10 numbers in cell 1
cinfo(1,2) = {1:20}; %// store vector of 20 numbers in cell 2
amp1 = cinfo(1,1); %// single cell containing a length-10 numeric vector
amp2 = cinfo(1,2); %// single cell containing a length-20 numeric vector
if isequal(amp1,amp2)
%// ...
In this example, which parallels your code, amp1 and amp2 are cell arrays consisting of a single cell which contains a numeric vector. Another possibility is to directly store each cell's contents into amp1, amp2, and then compare them:
amp1 = cinfo{1,1}; %// length-10 numeric vector
amp2 = cinfo{1,2}; %// length-20 numeric vector
if isequal(amp1,amp2)
%// ...
Note that even in this case, the comparisons amp1==amp1 or all(amp1==amp2) would give an error, because the vectors have different sizes.

find top n numeric cells in a cell array

Hi I have a cell array 2 x 1000. the first column holds numeric (double) values, the second holds a string. i would like the find all cells in the first column that are above a certain value, and bring back the corresponding cells in the second column. I have tried strcamp and various others but obviously they are for strings. I also tried doing
sortrows(mycell(1,:));
so i could pick the first 50 rows off or whateever, but this didn't seem to order the cell array. but really i would like to specifiy a threshold on the first column of the cell array.
How do I do this?
thanks.
If C is your cell array:
nums = [C{:,1}];
{:} converts C into a comma separated list (so {:,1} only converts the first column) and then [] collects the results into a normal array. After that it's simple:
index = nums > Threshold;
C(index,:)
OR in a one liner:
C([C{:,1}] > Threshold, :) %// Or C([C{:,1}] > Threshold, 2) as Luis said