MATLAB Answers

Subscripted assignment dimension mismatch.

1 view (last 30 days)
Walker Pride
Walker Pride on 4 Apr 2020
Commented: Walker Pride on 4 Apr 2020
I am a beginner programmer, but feel like I am missing something pretty fundamental here.
I am trying to make a function that takes 2 variables:
  • a string str
  • an integer N
It should then make a 1xN matrix containing the input string at each index and output the matrix.
function bigstring = string_multiplication(str,N)
bigstring(1:N) = str;
disp(bigstring);
end
When I call the function in the command window, I get the following message:
>> string_multiplication('Name',5)
Subscripted assignment dimension mismatch.
Error in string_multiplication (line 8)
bigstring(1:N) = str;
I have also tried predefining 'bigstring = zeros(1,N)' and using a for loop and get similar results.

  0 Comments

Sign in to comment.

Answers (1)

Fabio Freschi
Fabio Freschi on 4 Apr 2020
You can use repmat and create a char array
function bigstring = string_multiplication(str,N)
bigstring = repmat(str,N,1);
disp(bigstring);
end

  1 Comment

Walker Pride
Walker Pride on 4 Apr 2020
Thanks, Fabio!
Since I am looking for an 1xN array instead of Nx1, I think I could just flip the N,1 arguments in repmat.
Also, I figured out that single quotations ('Name') create a char datatype. To create a string datatype I needed to use double quotations ("Name").
When 'Name' = str, str is a 1x4 char (instead of a 1x1 string that I would get if I input "Name")
Then when I set bigstring(1:N) = str, each element of bigstring would try to store a 1x4 matrix instead of 1x1.
I ended up fixing it with the following code:
function bigstring = string_multiplication(str,N)
str = string(str);
bigstring = string(zeros(1,N));
for i = 1:N
bigstring(1,i) = str;
end
disp(bigstring);
end
This way whatever is input for str it is automatically converted into a 1x1 string.
This also works:
function bigstring = string_multiplication(str,N)
str = string(str);
bigstring(1:N) = str;
disp(bigstring);
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!