Borrar filtros
Borrar filtros

removing strings on several calls of function

1 visualización (últimos 30 días)
Max
Max el 10 de Nov. de 2015
Comentada: Stephen23 el 10 de Nov. de 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

Respuestas (2)

Guillaume
Guillaume el 10 de Nov. de 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 el 10 de Nov. de 2015
Editada: Thorsten el 10 de Nov. de 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 comentarios
Guillaume
Guillaume el 10 de Nov. de 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
Stephen23 el 10 de Nov. de 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):

Iniciar sesión para comentar.

Categorías

Más información sobre String Parsing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by