Index of Matching String in Cell Array

12 views (last 30 days)
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
end
end
%%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.

Accepted Answer

Vaibhav Tomar
Vaibhav Tomar on 4 Jul 2019
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
#include<stdio.h>
#include<string.h>
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");
else
printf("Strings are unequal");
printf("\nValue returned by strcmp() is: %d" , res);
return 0;
}
  1 Comment
SJ Won
SJ Won on 5 Jul 2019
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.

More Answers (1)

Walter Roberson
Walter Roberson on 4 Jul 2019
Use strcmp() or strcmpi() to compare character vectors.

Categories

Find more on Labels and Annotations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!