Matrix manipulation using strcmp

3 次查看(过去 30 天)
Forgive me if this is a simple question that I should be able to answer myself, but I've been struggling with the proper use of this for a few days now. I'm a relatively novice MatLab user.
I have a 2xn matrix. The left column is made up of strings, the right values associated with those strings, like this
OL 4
WR 7
OL 3
AT 2
What I've been trying to do is use strcmp to pick a particular sring and then return its associated value in a new 2xm matrix consisting solely of the string (for example 'OL' and the values associated with each.
This seems like a simple problem, however, I'm stuck.
Thanks in advance for any help you can give me.

采纳的回答

Thomas
Thomas 2012-3-30
a = {'OL',4;'WR',7;'OL',3;'AT',2}
c=arrayfun(@(x) strcmp(x,'OL'),{a{:,1}});
d=a(c,2)

更多回答(1 个)

Honglei Chen
Honglei Chen 2012-3-30
a = {'OL',4;'WR',7;'OL',3;'AT',2}
b = a(cellfun(@(x) strcmp(x,'OL'),{a{:,1}}),:)
  2 个评论
Zach
Zach 2012-3-30
This answer seems correct. However, I'm getting an error that 'g' is undefined. I tried to define it as g = [], but that doesn't work and obviously I'm not understanding what the variable, g, is.
Any expansion on this would be appreciated.
Thanks again for your help.
Honglei Chen
Honglei Chen 2012-3-30
sorry, had a typo, I updated the answer

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by