Extract a specific part of cell array values - matlab

I have a cell array with values similar to the following one
13:41:54.879
I would like to extract only 13:41 part of the given value and mitigate the rest. I tried various combinations of extractBefore() and extractAfter() but couldn't get it.

You can use a regular expression to match the pattern "digits, colon, digits":
c = {'13:41:54.879', '1:22:33.45679'};
result = regexp(c, '\d+:\d+', 'match', 'once');
gives
result =
1×2 cell array
{'13:41'} {'1:22'}

Related

(Matlab) How to check if cell array contains string

I am trying to grab data from an excel spread sheet and grab only the information from cells that match a string. Eg. if cell A10 contains the word 'Canada' it should return that cell.
I have tried using strcmp(https://www.mathworks.com/help/matlab/ref/strcmp.html) to check if string in argument 1 is contained in a cell array containing many strings, the second argument
[num,txt,raw] = xlsread('\\Client\C$\Users\Fish\Desktop\dataset\dataset.csv');
mytable = cell(raw);
for i = 1:54841
array_index = i;
string_index = mytable(i,2);
string_eastern = {'Canada', 'Ontario'};
if strcmp(string_index,string_eastern);
fprintf('%d\n',array_index)
end
end
In the above example if my string_eastern only contains one element, say 'Canada', it will return the index value of every instance of 'Canada'. If I add more elements I expect it would return index values for every instance where string_index would match with a string contained in string_eastern. However I get no results at all if I add more elements.
Pretty much I wanted to check my string_index agaisnt string_eastern, if the values match then I want it to return that cell value. This works when string_eastern is only 1 element but does not work with more than 1.
To access cell contents, use the curly brackets {}. So if I wanted to access the first element of my cell, I would say this:
string = cell{1};
Read more on the MATLAB Documentation about cells to learn more and to answer any of your further questions.

Split a Cell Array

I have a 150X1 cell array. Within the array there are multiple data types. The first cell contains 0.9VA = 1.012207; the second: 0.9VA_CLK = 0.020752; and so on like this (for the most part). I would like to split the cell into two cells using the = as the delimiter. Thus, {1,1}: 0.9VA and {1,2}: 1.012207; {2,1}: 0.9VA_CLK and {2,2}: 0.020752; so on and so forth. I have tried converting them to strings and then using strsplit; however, I run into problems because the string arrays are variable in size.
If there is any other information that I can provide please let me know. Thank you for your help and time in advance.
You can indeed apply strsplit to each of the strings (char arrays) in the cell array. To do so, you can use cellfun:
c{1} = '0.9VA = 1.012207';
c{2} = '0.9VA_CLK = 0.020752';
c{3} = 'CSIPhgenSWoffList = [0, 0, 0, 0]';
c{4} = 'SomethingElse = [0.020752, 0.24564]';
c = cellfun(#(x)strsplit(x,'='),c,'UniformOutput',false);
c = cat(1,c{:});
I use a small example cell array c here, containing four strings, I hope this is representative. I apply strplit to each cell in c using cellfun(x,'='), which splits at the equal sign and returns a cell array with cell arrays. That is, each string in c is turned into a cell array with 2 strings (e.g. '0.9VA ' and ' 1.012207'. This does leave some spaces at the beginning and end of the strings.
The next line, cat, converts this cell array of cell arrays into a two-dimensional cell array. The final output is a cell array c containing the same number of rows as the original cell array, and with 2 columns. The first column corresponds to the part before the equal sign, the second column to the part after the equal sign.
To remove the spaces, you can use cellfun again, with strtrim:
c = cellfun(#strtrim,c,'UniformOutput',false);

How to display selected entries of an array of structures in MATLAB

Suppose we have an array of structure. The structure has fields: name, price and cost.
Suppose the array A has size n x 1. If I'd like to display the names of the 1st, 3rd and the 4th structure, I can use the command:
A([1,3,4]).name
The problem is that it prints the following thing on screen:
ans =
name_of_item_1
ans =
name_of_item_3
ans =
name_of_item
How can I remove those ans = things? I tried:
disp(A([1,3,4]).name);
only to get an error/warning.
By doing A([1,3,4]).name, you are returning a comma-separated list. This is equivalent to typing in the following in the MATLAB command prompt:
>> A(1).name, A(3).name, A(4).name
That's why you'll see the MATLAB command prompt give you ans = ... three times.
If you want to display all of the strings together, consider using strjoin to join all of the names together and we can separate the names by a comma. To do this, you'll have to place all of these in a cell array. Let's call this cell array names. As such, if we did this:
names = {A([1,3,4]).name};
This is the same as doing:
names = {A(1).name, A(3).name, A(4).name};
This will create a 1 x 3 cell array of names and we can use these names to join them together by separating them with a comma and a space:
names = {A([1,3,4]).name};
out = strjoin(names, ', ');
You can then show what this final string looks like:
disp(out);
You can use:
[A([1,3,4]).name]
which will, however, concatenate all of the names into a single string.
The better way is to make a cell array using:
{ A([1,3,4]).name }

Function to split string in matlab and return second number

I have a string and I need two characters to be returned.
I tried with strsplit but the delimiter must be a string and I don't have any delimiters in my string. Instead, I always want to get the second number in my string. The number is always 2 digits.
Example: 001a02.jpg I use the fileparts function to delete the extension of the image (jpg), so I get this string: 001a02
The expected return value is 02
Another example: 001A43a . Return values: 43
Another one: 002A12. Return values: 12
All the filenames are in a matrix 1002x1. Maybe I can use textscan but in the second example, it gives "43a" as a result.
(Just so this question doesn't remain unanswered, here's a possible approach: )
One way to go about this uses splitting with regular expressions (MATLAB's strsplit which you mentioned):
str = '001a02.jpg';
C = strsplit(str,'[a-zA-Z.]','DelimiterType','RegularExpression');
Results in:
C =
'001' '02' ''
In older versions of MATLAB, before strsplit was introduced, similar functionality was achieved using regexp(...,'split').
If you want to learn more about regular expressions (abbreviated as "regex" or "regexp"), there are many online resources (JGI..)
In your case, if you only need to take the 5th and 6th characters from the string you could use:
D = str(5:6);
... and if you want to convert those into numbers you could use:
E = str2double(str(5:6));
If your number is always at a certain position in the string, you can simply index this position.
In the examples you gave, the number is always the 5th and 6th characters in the string.
filename = '002A12';
num = str2num(filename(5:6));
Otherwise, if the formating is more complex, you may want to use a regular expression. There is a similar question matlab - extracting numbers from (odd) string. Modifying the code found there you can do the following
all_num = regexp(filename, '\d+', 'match'); %Find all numbers in the filename
num = str2num(all_num{2}) %Convert second number from str

search through cell elements that contain a string, then delete it

Hi I want to search a cell array for any elements containing the letter 'x'. I can delete a cell element by doing the following:
mycell(3) = []
but trying to search through the elements id the difficult part. I am using:
offending_cell = strcmp('x', mycell);
however this is just picking out all elements regardless of x appearing in them. Anyone have any suggestions?
There you go:
ind = (~cellfun('isempty',(regexp(mycell,'x'))));
This gives logical indices for cells that contain 'x'. If you want to delete those cells:
mycell(ind) = [];
The problem with you apporach was that strcmp looks for exact matching, not if the string contains a given character.