Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Subscripted assignment dimension mismatch.

2 ビュー (過去 30 日間)
Walker Pride
Walker Pride 2020 年 4 月 4 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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.

回答 (1 件)

Fabio Freschi
Fabio Freschi 2020 年 4 月 4 日
You can use repmat and create a char array
function bigstring = string_multiplication(str,N)
bigstring = repmat(str,N,1);
disp(bigstring);
end
  1 件のコメント
Walker Pride
Walker Pride 2020 年 4 月 4 日
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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by