0

文字列の単一のセル配列が与えられた場合、その単一のセル配列をアルファベット順に返すように、2 つの文字列の要素を比較する Matlab 関数を書きたいと考えていますfunction({'car','apple','bus'})。 2 つの文字列を互いに比較し、数値を割り当てます。

function [ out ] = comparestrings( a,b )

for k=1:min(length(a),length(b))

    if a(1,k)<b(1,k)
       out=1;
       return
    elseif b(1,k)<a(1,k)
        out=0;
        return
    end    
end
    if length(a)<length(b)        
       out=1;
    else out=0;      
    end   
end

しかし、Matlab でプログラムを実行しようとすると、次の行にエラーがあると表示されます。

if a(1,k) < b(1,k)

なぜこれができるのかわかりませんか?

4

3 に答える 3

2

Functions like sort, unique, and ismember are defined not only for numbers, but also for cell arrays of strings. Therefore, I don't think it is necessary to convert your strings to numbers.

As to your error - you need to supply strings, not cell arrays, i.e.

myCellArray = {'car','apple'}

compareStrings(myCellArray{1},myCellArray{2})

With the curly brackets, you access the contents of the elements of the cell array, while with parentheses, you'd be supplying cells, and < is not defined for cells.

于 2013-02-22T11:56:10.817 に答える
1

GNU/Linux の Matlab R2010a でコードを実行しましたが、正しく動作します。関数を というファイルに保存したcomparestring.mので、次の方法で呼び出すことができます。

comparestrings('car','apple')

ans =

     0

comparestrings('apple', 'car')

ans =

     1

関数を適切に呼び出していない可能性がありますか?

とにかく、自分で関数を作成する必要がない場合は、Matlab の組み込み関数を使用できますsort

sort({'car','apple','bus'})

ans = 

    'apple'    'bus'    'car'
于 2013-02-22T11:55:09.557 に答える
0

ところで、それを行う strcmp と呼ばれる matlab の関数があります。

于 2013-02-23T09:47:04.983 に答える