Clear Filters
Clear Filters

removing strings on several calls of function

1 view (last 30 days)
Max
Max on 10 Nov 2015
Commented: Stephen23 on 10 Nov 2015
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

Answers (2)

Guillaume
Guillaume on 10 Nov 2015
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 on 10 Nov 2015
Edited: Thorsten on 10 Nov 2015
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 Comments
Guillaume
Guillaume on 10 Nov 2015
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!