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 (최근 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
채택된 답변
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
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 Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!