필터 지우기
필터 지우기

How do I prompt for a variable in one script and use it in another

조회 수: 4 (최근 30일)
Will
Will 2023년 11월 27일
댓글: Stephen23 2023년 11월 28일
My first script which prompts the user is as follows
%this main script calls to one main function(isPalindrome) with a subfunction(removeNonAlpha)
%this script prompts the user for a character vector to test for being a
% palindrome
fprintf('A palindrome is a word, phrase, or sequence that reads the same backward as forward\n')
str=input('Enter text to test for palindrome:','s');
welp=isPalindrome;
if welp==1
fprintf('Heyy!! %s is a palindrome :) ',str)
else
fprintf('Dang :( %s is not a palindrome ',str)
end
The function that the first script calls is as follows
%this function tests whether a character vector is a palindrome
function Welp=isPalindrome(~)
strrevised=removeNonAlpha(str);
if strrevised==fliplr(strrevised)
Welp=1;
else
Welp=0;
end
end
function strrevised=removeNonAlpha(str)
%this function takes in a string and revises it to remove blanks and to
%remove numbers ie take only alpha characters
str2=isletter(str);
strrevised=str(str2);
end
when I run my program i get the error "unrecognized function or variable 'str' "
how can i make it recognize the first variable in the function the script calls
second question (kind of)how can I make welp=1 if my character vector is blank ie if str=[] because right now it would delete a blank vector because it's not a letter.
PSA sorry this question is a lot lol
  댓글 수: 1
Stephen23
Stephen23 2023년 11월 28일
"how can i make it recognize the first variable in the function the script calls "
Why not simply pass WELP as an input argument, just as the MATLAB documentation recommends?:

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2023년 11월 27일
After the line
function Welp=isPalindrome(~)
insert
str = evalin('caller', 'str');
or
str = evalin('base', 'str');
Neither of these is recommended. Recommended would be to have used
welp=isPalindrome(str);
with
function Welp=isPalindrome(str)
  댓글 수: 2
Walter Roberson
Walter Roberson 2023년 11월 27일
For your second question:
change
if strrevised==fliplr(strrevised)
to
if isequal(strrevised, fliplr(strrevised))
Where comparing '' == fliplr('') gives an empty logical result, using isequal() gives 1 (true)
Will
Will 2023년 11월 27일
the second method works well. thank you, much appreciated :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by