removing strings on several calls of function
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposte (2)
Guillaume
il 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
0 Commenti
Thorsten
il 10 Nov 2015
Modificato: Thorsten
il 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 Commenti
Guillaume
il 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.
Stephen23
il 10 Nov 2015
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):
Vedere anche
Categorie
Scopri di più su Get Started with MATLAB in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!