update: using num2str instead of sprintf works, however on 2nd loop of the for statement, error "index exceeds number of array elements" occurs
Compare digits of 2 strings
1 view (last 30 days)
Show older comments
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
Accepted Answer
Tien
on 30 Nov 2023
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 Comments
Stephen23
on 30 Nov 2023
Edited: Stephen23
on 30 Nov 2023
"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:
More Answers (0)
See Also
Categories
Find more on Logical 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!