Reputation: 1
I have a column of strings in a matrix
X = ['apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)'; 'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)' ]
I need to create another column of matrix to redefine the content of X.
For example, I want MATLAB to redefine 'apple' as 1 and 'orange' as 2. So in the end I would expect something like this:
[1; 1; 1; 2; 2; 2]
However, the MATLAB could not read the string when I read the column of strings:
theMatrix = xlsread(myFile.xls);
for i = numTotalTrials;
X = theMatrix(i,2)
> X = Nan
Further, I am using strfind
to redefine the column:
t = strfind(X,'a');
if t == 1
newColumn = 1
else
newColumn = 2
end
Does MATLAB work this way? Thanks!
Upvotes: 0
Views: 101
Reputation: 124563
Another solution using regular expressions:
%# note the use of cell-arrays
X = {'apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)';
'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)'};
%# match either apples or oranges
m = regexp(X, '^(apple|orange)', 'match', 'once');
%# which one was found
[~,loc] = ismember(m, {'apple','orange'})
The result:
>> loc
loc =
1
1
1
2
2
2
Upvotes: 1
Reputation: 8527
Don't know, if this is exaclty what you are looking for but starting with
X = ['apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)';
'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)'];
I would define an output vector result
, loop over the input and just look for the
desired strings using strfind
which might look like
result = zeros(size(X, 1), 1);
for row = 1 : size(X, 1)
if ~isempty(strfind(X(row,:), 'apple'))
result(row) = 1;
elseif ~isempty(strfind(X(row,:), 'orange'))
result(row) = 2;
end
end
This will return
result = [1; 1; 1; 2; 2; 2];
Upvotes: 0