Mathlete
Mathlete

Reputation: 163

Matlab function to compare the elements of two strings

I want to write a Matlab function that compares the elements of two strings, so that given a single cell array of strings, it will return that single cell array but in alphabetical order eg function({'car','apple','bus'}) so I have written a sub-function that compares the elements of two strings against one another and assigns a numerical value:

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

But when I try and run my program in Matlab, it says there is an error in the line

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

I have no clue why this could be?

Upvotes: 0

Views: 1426

Answers (3)

DanielTheRocketMan
DanielTheRocketMan

Reputation: 3249

By the way, there is a function in matlab called strcmp that does that!

Upvotes: 0

Jonas
Jonas

Reputation: 74940

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.

Upvotes: 2

Digna
Digna

Reputation: 882

I have run your code in Matlab R2010a under GNU/Linux and it works correctly. I have saved your funcion in a file called comparestring.m, and then I can call it the following way:

comparestrings('car','apple')

ans =

     0

comparestrings('apple', 'car')

ans =

     1

Maybe you are not calling your function properly?

Anyway if you do not need to create a function yourself you can use Matlab's built-in function sort:

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

ans = 

    'apple'    'bus'    'car'

Upvotes: 1

Related Questions