MATLAB Answers

SJ Won

Index of Matching String in Cell Array

Asked by SJ Won
on 4 Jul 2019
Latest activity Commented on by SJ Won
on 5 Jul 2019
I'm trying to open up a file and read the cities listed along the first row and column. In between them are the numbers that indicate the distance between the two cities.
Here is what I did:
function distance = get_distance(city1, city2)
[~,~,everything] = xlsread('Distances.xlsx');
%%looks for row number of city1
for i = 1:row
if city1 == everything{i, 1}
x_loc = i
%%alternative: x_index = find([everything{:,1}]=='city1')
I looked into the first column through each rows to see where the strings match between city1 and the name inside the excel sheet. However, matlab is telling me the dimensions of the matrix must match
"Matrix dimensions must agree.
Error in get_distance (line 8)
if city1 == everything{i, 1} "
I tried using an alternative line which is much more succinct, as shown in the last comment line. That also gave same error
Matrix dimensions must agree.
Error in get_distance (line 7)
x_index = find([everything{:}]=='city1')
I don't understand why the dimensions don't match. Aren't they both the same value? I tried evaluating each city1 and everything{i,1} separately but it gave the same output so I don't understand the issue.


Sign in to comment.


2 Answers

Answer by Vaibhav Tomar on 4 Jul 2019
 Accepted Answer

Hey, in this problem you just need to implement the use of one string function. The function is strcmp()
Here's an implementation in C/C++:
// C program to illustrate
// strcmp() function
int main()
char leftStr[] = "g f g";
char rightStr[] = "g f g";
// Using strcmp()
int res = strcmp(leftStr, rightStr);
if (res==0)
printf("Strings are equal");
printf("Strings are unequal");
printf("\nValue returned by strcmp() is: %d" , res);
return 0;

  1 Comment

I can see how it's easier to use strcmp but why couldn't I also have done it the way I did above?

Sign in to comment.

Answer by Walter Roberson
on 4 Jul 2019

Use strcmp() or strcmpi() to compare character vectors.


Sign in to comment.