Help creating loop that converts text to numbers
조회 수: 10 (최근 30일)
이전 댓글 표시
Hi, this is a follow-up on a question I asked yesterday.
I have a loop that asks the user to input sentences until the word 'end' is typed.
After the loop has ended, I want it to display the sentences typed as inegers, using the "char" command
ex
char([101 102 103])
but reversed since it would be taking the letters and converting them to integers.
Here is what I have so far.
The other loop to execute this specific function is probably extremely wrong but I am an absolute beginner and was just trying to follow a similar format to the first loop I recieved some help with yesterday.
clc
N=input('what is N?: ') %establishes N
all_A = {};
while true
A = input('give me a sentence!: ','s'); %asks user for sentence input
if strcmpi(strtrim(A), 'end');
break;
end %will end the loop if end is typed
all_A{end+1} = A;
end
all_B={};
while false
B= input('give me a sentence!: ','s');
if strcmpi(strtrim(B));
num2str(char[B])
end
end
댓글 수: 0
답변 (1개)
dpb
2021년 10월 22일
>> A='Now is the time...';
>> format short
>> disp(double(A))
78 111 119 32 105 115 32 116 104 101 32 116 105 109 101 46 46 46
>> char(double(A))
ans =
'Now is the time...'
>>
The converse of char() is simply one of the numeric classes; by default everything numeric in MATLAB is double so I used it. Could just as well have used
>> int8(A)
ans =
1×18 int8 row vector
78 111 119 32 105 115 32 116 104 101 32 116 105 109 101 46 46 46
>>
댓글 수: 4
dpb
2021년 10월 23일
As noted, UNTESTED code...I had never tried double on a string; I presumed it would behave as expected; turns out it doesn't. A string variable is higher abstraction and contains a cellstr() underneath, but to convert to underlying numeric turns out you have to explicitly address that content -- "Use the curlies, Luke!"
disp(double(A{i})
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!