how I do it. the function is called a string is passes a numbr

2 ビュー (過去 30 日間)
Dezdi
Dezdi 2018 年 11 月 19 日
コメント済み: dpb 2018 年 11 月 20 日
how could I do this one
looks like
functionname('hello')
ans= hello1
functionname('john')
ans= john2
...
many thanks
  1 件のコメント
dpb
dpb 2018 年 11 月 19 日
Which number, in particular? Any one, random, user-specified, sequential since last invocation as shown above (requires some extra logic to keep track of that and over what population if so)...???
So many questions, so little known... :)
s=sprintf('%s%d',str,randi(1000);
might give you some ideas, however...

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 11 月 20 日
function out = myfun(inp)
persistent cnt
if nargin==0 || isempty(cnt)
cnt = 0;
end
cnt = cnt+1;
assert(cnt<=5,'You already have five words')
out = sprintf('%s%d',inp,cnt);
end
And tested:
>> myfun('anna')
ans = anna1
>> myfun('bob')
ans = bob2
>> myfun('cathy')
ans = cathy3
>> myfun('david')
ans = david4
>> myfun('evalyn')
ans = evalyn5
>> myfun('frog')
error: You already have five words
  1 件のコメント
Dezdi
Dezdi 2018 年 11 月 20 日
編集済み: Dezdi 2018 年 11 月 20 日
thank you
Is there any way to write message here not just post?

サインインしてコメントする。

その他の回答 (2 件)

Luna
Luna 2018 年 11 月 20 日
Hello Dezdi,
You can do it by first collecting your inputs in a cell array and then call your function in a for loop with 5 elements.
inputStr = {'John','Mary','Kayle','Adam','David'};
for i = 1:5
out = myFunc(inputStr,i)
end
function outputStr = myFunc(inputStr,i)
outputStr = [inputStr{i}, sprintf('%d',i)];
end

Preethi
Preethi 2018 年 11 月 20 日
hi,
check this
function test_preethi(str)
persistent i
if isempty(i)
i=1;
else
if i <=5
sprintf('%s%d',str,i)
i=i+1 ;
else
sprintf('limit reached')
end
end
  3 件のコメント
Dezdi
Dezdi 2018 年 11 月 20 日
編集済み: Dezdi 2018 年 11 月 20 日
thank you it works for me sorry I am new here can't accept all of you answers.
dpb
dpb 2018 年 11 月 20 日
This particular function only "works" in that it creates the string internal to the function but you can't get at the result.
The use of persistent is good in saving the previous value, unfortunately the function has no mechanism by which the variable can be reset/re-initialized so without external intervention once the sequence is full, there's no going forward...details, details! :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by