Index of Matching String in Cell Array

6 次查看(过去 30 天)
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.

采纳的回答

Vaibhav Tomar
Vaibhav Tomar 2019-7-4
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 个评论
SJ Won
SJ Won 2019-7-5
I can see how it's easier to use strcmp but why couldn't I also have done it the way I did above?

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2019-7-4
Use strcmp() or strcmpi() to compare character vectors.

类别

Help CenterFile Exchange 中查找有关 Labels and Annotations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by