필터 지우기
필터 지우기

how to combine strings that are generated inside a function?

조회 수: 1 (최근 30일)
Roxanne Esguerra
Roxanne Esguerra 2020년 7월 22일
댓글: Roxanne Esguerra 2020년 7월 23일
Hi, I have this code that must randomly scramble the letters of the string input and return the result as a whole word. However, this returns the letters one by one.
function royalscramble(str)
exchange = randperm(length(str));
for i=1:length(str)
str(exchange(i))
end
end
I tried additions to the code and it worked. Here it is.
function scrambled = royalscramble(str)
exchange = randperm(length(str));
scrambled = '';
for i=1:length(str)
scrambled = str(exchange(i));
end
end
However, the function must not be called like that. I mean, it should not have scrambled =
It should be like this and returns this kind of result:
>> royalscramble('fantastic')
ans =
safntcait
>> royalscramble ('hello')
ans =
hleol
What should I add/replace from my first code? Thanks!

채택된 답변

KSSV
KSSV 2020년 7월 22일
function scrambled = royalscramble(str)
exchange = randperm(length(str));
scrambled = str(exchange) ;
end
  댓글 수: 4
Stephen23
Stephen23 2020년 7월 22일
"but I need a function that doesn't need "scrambled=" to be called... Is that possible?"
It is not required to call a function with an output argument:
But if you want any value returned, you will have to declar an output argument:
Roxanne Esguerra
Roxanne Esguerra 2020년 7월 23일
Thanks! I found my mistake. I have always called the function without putting '--' in the string. That's why it didn't work and resulted to this.
>> royalscramble(fantastic)
Unrecognized function or variable 'fantastic'.
>> scrambled = royalscramble(fantastic)
Unrecognized function or variable 'fantastic'.
Thank you so much :)

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by