MATLAB: I don’t know what is wrong with this code? I have to read an excel file and return the distance between two places. And the output is always -1. I’ve attached the file Distances.xlsx

excelindexing

function distance = get_distance(source,dest)
[~,~, raw] = xlsread('Distances.xlsx');
row1 = raw{1,1:end};
column1 = raw{1:end,1};
pos_row = -1;
pos_col = -1;
for i = 1:length(column1)
if strcmpi(source,column1(i)) == 1
pos_row = i;
end
end
for j = 1:length(row1)
if strcmpi(dest,row1(j)) == 1
pos_col = j;
end
end
if (pos_row == -1) || (pos_col == -1)
distance = -1;
else
distance = raw{pos_row,pos_col};
end

Best Answer

Try this
[~,~, raw] = xlsread('Distances.xlsx');
a = 'Billings, MT';
b = 'Amherst, NY';
d = get_distance(a, b, raw)
function distance = get_distance(source, dest, raw)
row1 = raw(1,2:end);
column1 = raw(2:end,1);
pos_row = find(ismember(row1, source))+1;
pos_col = find(ismember(column1, dest))+1;
if isempty(pos_row) || isempty(pos_col)
distance = -1;
else
distance = raw{pos_row,pos_col};
end
end
Result
>> d
d =
1926
If you want to call get_distance() several times, then it is better to move the xlsread() out of the function.
Related Question