Index of Matching String in Cell Array
Show older comments
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
More Answers (1)
Walter Roberson
on 4 Jul 2019
1 vote
Use strcmp() or strcmpi() to compare character vectors.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!