0

I am learning MATLAB and was trying to code the following. Write a function called “buildrandomstrings” that will receive as input an integer n.Now If n is +ve: it will create and return a cell array with strings of random characters of increasing lengths, from 1 to n. Each string will be constituted by the previous random string plus an extra random character.

Now my code-

function buildrandomstrings = buildrandomstrings(inchar, posint)
% Creates a cell array with strings of increasing
% lengths, from 1:n, starting with inchar
% Format of call: buildstr(input char, n)
% Returns cell array with n strings

buildrandomstrings= cell(1, posint);
inchar = char(inchar-1);

strin = '';

for i = 1:posint
    strin = strcat(strin, char(inchar+i));
    buildrandomstrings{i} = strin;
end
end

But I am getting the following error which makes no sense to me. Even though I have looked everywhere.

buildrandomstrings(4)

Not enough input arguments.

Error in buildrandomstrings (line 7)

buildrandomstrings= cell(1, posint);

When I do ctrl+click I get the following.

Creates a cell array with strings of increasing lengths, from 1:n, starting with inchar Format of call: buildstr(input char, n)
Returns cell array with n strings

2
  • @SardarUsama I am not running it I am calling the function itself but its not working. Commented Nov 18, 2018 at 4:40
  • @SardarUsama I I missed the the quote on char for some reason. Thanks. Commented Nov 18, 2018 at 4:45

1 Answer 1

1

I guess you run buildrandomstrings(4). However, you need to provide two arguments as defined by your function function buildrandomstrings = buildrandomstrings(inchar, posint).

Try:

buildrandomstrings('a', 4)

Output:

ans =
  1×4 cell array
    {'a'}    {'ab'}    {'abc'}    {'abcd'}
Sign up to request clarification or add additional context in comments.

2 Comments

No problem. Note, your way of generating a random string char(inchar+i) is not perfect. Consider using randi():)
To get a string that is the previous string minus the last character, you can use slicing. For example, buildrandomstrings{i-1} = buildrandomstrings{i}(1:end-1).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.