本文介绍了字符串单元阵列 - 检查在Matlab元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Matlab的,如果我有一个字符串单元阵列,我怎么能检查是否例如第3行第1列等于某个给定的字符串,例如'ABC'

例如, myArray的(3,1)=='ABC'给我一个错误:

解决方案

That's because you need to use {curly braces} in order to access the content of the cell array.

Using (regular brackets) indexes the actual cell, which in your case contains a string. Moreover, in order to check for the presence of strings I recommend using strcmp or maybe strfind.

Therefore use this:

strcmp(myArray{3,1},'ABC')

Check here for infos about indexing into cell arrays.

EDIT (following comments)

Using logical == in order to find for strings into a cell array is not safe, because using this operator splits the strings and compares every letter forming it, as opposed to strcmp and the likes, that checks the whole string.

Consider this code, where I put some strings into myArray:

myArray = {'A' 'B' 'ABC' 'CBA' 'ABC'}.'

myArray =

    'A'
    'B'
    'ABC'
    'CBA'
    'ABC'

If we apply == on this cell array of strings as follows:

Check_31 = myArray{3,1} == 'ABC'

Check_41 = myArray{4,1} == 'CB_'

Matlab returns those 2 logical vectors:

Check_31 =

     1     1     1


Check_41 =

     1     1     0

So as you see, the character "_" is not the last element of the string present in the cell {4,1}.

Now if we use strcmp (on the whole cell array; we don't need to index specific cells to check whether some string is present):

Check_ABC = strcmp(myArray,'ABC')

We also get a logical vector, but this time not referring to the 3 letters forming the string inside the cell, but rather referring to the cell array itself and whether 'ABC' is present or not. The result is this:

Check_ABC =

     0
     0
     1
     0
     1

Which makes sense, since 'ABC' is indeed present in cells {3,1} and {5,1}.

Hope that's clearer!

这篇关于字符串单元阵列 - 检查在Matlab元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:14