Compare digits of 2 strings

1 次查看(过去 30 天)
Taiga
Taiga 2023-11-30
编辑: Stephen23 2023-11-30
Looking to compare a string of pi to a calculated string to check for digit similarity between the two (ie 3.1415 compared to 3.1426, 3 digits accurate)
The idea is to put it into a table that can be read as 3 columns with "n values", "calculated values", "digit accuracy".
my issue is i dont know how to look at each character of the strings to compare, as when i try to get the 1st digit it responds with the whole string.
Example code:
clear; format longg;
calcPi=zeros(1, 4); digitAccuracy=zeros(1,4);
nrange=[1*10^2, 1*10^4, 1*10^6]; step=1;
piString=sprintf("%.14f", pi);%convert pi to a string with 14 decimals
for n=nrange
k=1:n;
sumEQ=sum(1./k.^2); %find (pi^2)/6
calcPi(step)=sqrt(6*(sumEQ)); %solve for pi
calcString=sprintf("%.14f",calcPi(step));%convert calcPi to string with 14 decimals
for i = 1:strlength(calcString) %loop for every digit of calcString
calcDigit=str2double(calcString(i)); %take i'th digit of calcString
piDigit=str2double(piString(i)); %take i'th digit of piString
if calcDigit == piDigit %are both i'th digits equal?
digitAccuracy(step) = 1+digitAccuracy(step); %if yes, increase counter by 1
end
end
step=step+1; %step increase for array indexing
end
  1 个评论
Taiga
Taiga 2023-11-30
update: using num2str instead of sprintf works, however on 2nd loop of the for statement, error "index exceeds number of array elements" occurs

请先登录,再进行评论。

采纳的回答

Tien
Tien 2023-11-30
Your calcString and piString are of string type. I believe you have to convert those strings to character vectors for the loop to work correctly. Simply change the double quote to single quote in the sprintf lines would do the trick:
piString=sprintf('%.14f', pi);
calcString=sprintf('%.14f',calcPi(step));
  2 个评论
Taiga
Taiga 2023-11-30
this worked perfectly, thanks! wasnt aware " and ' had specific differences
Stephen23
Stephen23 2023-11-30
编辑:Stephen23 2023-11-30
"wasnt aware " and ' had specific differences"
Completely different:
  • ' defines a character array, each element is exactly one character.
  • " defines a string scalar, each element is a container containing arbitrarily long text
This is explained in the documentation:

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by