removing strings on several calls of function

2 次查看(过去 30 天)
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by