Error using vertcat Dimensions of arrays being concatenated are not consistent.

3 views (last 30 days)
This seems to be a trivial problem but I am struggling to figure it out. Why is it that when I define
some_var = ['AB'; 'CD'; 'EF'],
then there is no error, but when I write
some_var_full = ['alpha beta'; 'gamma eps'; delta phi'], it generates an error mesage:
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
How can I fix it? Thank you so much in advance for helping me.

Accepted Answer

Chunru
Chunru on 15 Jul 2022
Edited: Chunru on 15 Jul 2022
% some_var = ['AB'; 'CD', 'EF']
% semicolon for new rows and comma for new coloumn. so the above is wrong
% The code below is OK (each row has same number of characters in order to
% form a 2d char array
some_var = ['AB'; 'CD'; 'EF']
some_var = 3×2 char array
'AB' 'CD' 'EF'
% some_var_full = ['alpha beta'; 'gamma eps'; 'delta phi']
% The above is wrong since the 1st line has more characters than other
% lines
% You can make each line has same number of characters
some_var_full = ['alpha beta'; 'gamma eps '; 'delta phi ']
some_var_full = 3×10 char array
'alpha beta' 'gamma eps ' 'delta phi '
% It is better to use string array
some_var_full = ["alpha beta"; "gamma eps"; "delta phi"]
some_var_full = 3×1 string array
"alpha beta" "gamma eps" "delta phi"

More Answers (1)

Walter Roberson
Walter Roberson on 15 Jul 2022
'AB' is a 1 x 2 array of character
'CD' is a 1 x 2 array of character
['AB';'CD'] is asking to vertically concatenate a 1x2 and a 1x2. The number of columns match so the result is well defined to create 2x2 array of character
'alpha beta' is a 1x10 array of character
'gamma eps' is a 1x9 array of character.
When you [;] those together you are asking to vertically concatenate a 1x10 array and a 1x9 array. The number of columns do not match so it is an error.
You might want to switch to using
some_var_full = ["alpha beta"; "gamma eps"; "delta phi"]
Now each of the rows is a 1x1 string() object instead of being character vectors.

Categories

Find more on Rubik's Cube in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by