フィルターのクリア

removing strings on several calls of function

1 回表示 (過去 30 日間)
Max
Max 2015 年 11 月 10 日
コメント済み: Stephen23 2015 年 11 月 10 日
I'm trying to remove strings once they have been called. And then I want to ignore an if statement on the next call of a function of a condition is met
For example
vowels= 'a', 'e', 'i','o','u'
newguess= %random vowel
if newguess is used at random say newguess ='e'
%delete newguess from vowels
end
And how do I make it so on the second call of the function that the vowels won't contain newguess and on the third call it won't contain the 2 previous guesses and so on Thanks

回答 (2 件)

Guillaume
Guillaume 2015 年 11 月 10 日
Simply pass in the vowel list to your function and return the shortened list as an output. On the next call to your function you pass in the shortened list:
function [vowels, eliminated] = randremove(vowels)
idx = randi(numel(vowels));
eliminated = vowels(idx);
vowels(idx) = [];
end
Then your main function:
vowels = 'aeiou';
while ~isempty(vowels)
[vowels, eliminated] = randremove(vowels);
fprintf('%c was removed from the list\n', eliminated);
end

Thorsten
Thorsten 2015 年 11 月 10 日
編集済み: Thorsten 2015 年 11 月 10 日
You can globally define the vowels
global vowels
vowels= {'a', 'e', 'i','o','u'};
And use a function that works on these vowels as follows
function myfun
global vowels
assert(numel(vowels) > 0, 'Number of vowels but be greater zero.')
i = randi(numel(vowels)); % pick a random vowel
randomvowel = vowels(i);
vowels(i) = []; % remove it from the list of vowels
disp(vowels)
As Guillaume suggested, you can do this without using global as follows
function vowels = myfun(vowels)
assert(numel(vowels) > 0, 'Number of vowels but be greater zero.')
i = randi(numel(vowels)); % pick a random vowel
randomvowel = vowels(i);
vowels(i) = []; % remove it from the list of vowels
disp(vowels)
In this version it is clear that myfun changes vowels.
  2 件のコメント
Guillaume
Guillaume 2015 年 11 月 10 日
no, no, no! Don't use global! Particularly, if you're learning matlab. There are too many pitfalls associated with global variables.
The proper way of doing this is to simply return the altered list in the function.
Stephen23
Stephen23 2015 年 11 月 10 日
Do NOT use globals! If you are a beginner learn to pass values properly, and not to use globals for everything. Globals are make for slow and buggy code, which is why they come in at number two on this list:
The best and recommended way to get values between workspace is to pass them as arguments:
Use of globals is not a good programming practice, which has been discussed many times on this forum (and other forums too):

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

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by