Operator '-' is not supported for operands of type 'string'. Matlab

8 views (last 30 days)
I am looking to use my code to calculate to implement a KNN classifier however I am getting an error when trying to calculate my equation for the Euclidean distance.
I am getting the following error:
Operator '-' is not supported for operands of type 'string'.
Error in A2Q1 (line 18) equation = sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2 + (a1-a2)^2 );
Please find the portion of my code with the error below and help me to fix it
while counter <= 13
counter = counter + 1;
x1 = table2array(T([counter],[1]));
y1 = table2array(T([counter],[2]));
z1 = table2array(T([counter],[3]));
a1 = table2array(T([counter],[4]));
**equation = sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2 + (a1-a2)^2 );**
result{counter} = equation;
end
resultcolumn = result';
The equation line is the one causing the error.

Answers (1)

Matt J
Matt J on 16 Jul 2021
Presumably it is because T contains strings, not numbers.
  3 Comments
Matt J
Matt J on 16 Jul 2021
Edited: Matt J on 16 Jul 2021
No, T would have to be a variable, not a file. I suggest you attach T in a .mat file so we can examine it together.
Walter Roberson
Walter Roberson on 16 Jul 2021
There are circumstances under which when you readtable() an excel file, that a variable can come out as string instead of numeric. In particular it can happen if there are multiple header rows, and it can also happen if one of the columns contains a mix of strings and numbers that happens to start with a number (thus confusing MATLAB into thinking that the first row is not header)

Sign in to comment.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!