erasing all the rows of a cell matrix that contain a specific string variable
2 views (last 30 days)
Show older comments
Dear all, I have a cell matrix where its first column is
'MATA'
[ NaN]
'PANWE 1'
' CONSISTENE'
' POPULAZE'
[ NaN]
‘MATA’
'PANWE 1'
' CONSISTENE'
' POPULAZE'
[ NaN]
I want to erase all the rows that contain the word “MATA”
cheers
Accepted Answer
per isakson
on 13 Jul 2012
Edited: per isakson
on 13 Jul 2012
Your solution is based on an undocumented behavior of strcmp. strcmp according to the documentation should not take a double nor a cell array of double, e.g. NaN, {NaN}.
The function, find, may be removed. I guess the Code Analyzer indicates that.
A = { 'MATA'
NaN
'PANWE 1'
' CONSISTENE'
' POPULAZE'
NaN
'MATA'
'PANWE 1'
' CONSISTENE'
' POPULAZE'
NaN };
match2 = find(strcmp(A(:, 1), 'MATA'));
A(match2,:)=[];
is_MATA = strcmp(A(:, 1), 'MATA');
A( is_MATA, : ) = [];
.
--- Cont. ---
I think your solution is risky (and incorrect). You cannot complain if TMW decides to block it and throw an error, but users of your code might blame you. Read the documentation on STRCMP. It is for strings.
There need to be a good reason to use strcmp like this - IMO.
Here is a code I came up with
is_string = cellfun( @(x) ischar( x ), A, 'uni', false );
is_MATA = cellfun( @(is,x) (is && strcmp(x,'MATA')), is_string, A );
A( is_MATA, : ) = [];
It's a bit complicated.
I have used strfind with flints (floating integers). There used to be a real performance advantage over find. I called it "us' trick" and I know how to find the trick in my code.
>> strfind( ( 65:75), 67 )
ans =
3
>> strfind( ( 65:75), (67:68) )
ans =
3
4 Comments
per isakson
on 15 Jul 2012
Edited: per isakson
on 15 Jul 2012
It depends on the context - the purpose of the code.
EDIT:
Thus, I have to start a discussion with Jan.
In case you anticipate that the code, which you are developing, will be used and maintained with future releases of Matlab then I would definitely recommend against using "strcmp(A(:,1),'MATA')".
On the other hand if you will use the code for a short period of time and then throw it away, why not use "strcmp(A(:,1),'MATA')".
END EDIT
However, I would not recommend that construct and it is because STRCMP is not intended for double.
What role does NaN play in the cell array, A? I would try replace NaN with a string of some kind. And why the the leading space in of some strings?
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!