How to use variable in a function?
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello. I am trying to make a function which will take strings as input (where string contains 3 characters: 0, +, -) and any '+' or '-' character will be replaced by '0'.
Now i want to add a variable which determines how many '+' or '-' will be replaced by '0'. But i am not getting any idea how to add it in the function. I want to add this variable because input_strings and working_variable will be changing continously. Following is my code:
function replacement_result = replacement(input_strings, working_variable)
for i1 = 1 : size(input_strings,1)
a = 0;
for j1 = size(input_strings,2): -1 : 1
if input_strings(i1,j1) == '0';
a = a+1;
else break,
end
end
for k1 = (size(input_strings,2)-a): -1 : 1
if input_strings(i1, k1) ~= '0'
input_strings(i1, k1) = '0';
else break,
end
end
end
replacement_result = input_strings;
If input_strings = [0+0-00-0+, +0+0-0+0-, -0-00-0+0], then if working_variable = 1, so replacement_result = [0+0-00-00, +0+0-0+00, -0-00-000]
If input_strings = [0+0-00-0+, +0+0-0+0-, -0-00-0+0], then if working_variable = 3, so replacement_result = [0+0000000, +0+000000, -00000000]
How can i add 'working_variable' in this function? Can any one please give me any idea?
0 Commenti
Risposta accettata
Geoff
il 24 Feb 2012
A lot of people may ignore this question because it's about programming rather than MatLab, specifically... But it would help you to know that MatLab has a lot of powerful functions and constructs that can do the work for you.
In your case, you can use cellfun to iterate over your cell of strings, find to search for the required number of +/- chars, and lambda functions to make the notation a little clearer.
function [replacement_result] = replacement(input_strings, working_variable)
replacement_result = cellfun( ...
@(x) replace_n(x,working_variable), ...
input_strings, 'UniformOutput', false );
end
function [str] = replace_n( str, n )
f = @(x) find( x=='-' | x=='+', n, 'last' );
str(f(str)) = '0';
end
Now you can do:
>> input_strings = {'0+0-00-0+', '+0+0-0+0-', '-0-00-0+0'};
>> replacement(input_strings,1)
ans =
'0+0-00-00' '+0+0-0+00' '-0-00-000'
>> replacement(input_strings,2)
ans =
'0+0-00000' '+0+0-0000' '-0-000000'
>> replacement(input_strings,10)
ans =
'000000000' '000000000' '000000000'
-g-
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Cell Arrays in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!