Hi I am trying to make a vector with char variable.

This is my code:

v = [h w]
t = v(1);

THe result is t='w'

Why is t not t='wudh2h2' ?

  • $\begingroup$ This will work as intended if instead of a vector you use cell arrays. Because MATLAB. $\endgroup$ – A_A Nov 13 '17 at 11:50

Because in Matlab you don't use matrices as an element of another matrix. You simply copy the whole matrix and and paste it everywhere when you have a usage like that.

The code you are looking for is like:

t = v(1:length(h));

that will do the work. The code basically means start from the 1'st item and keep going until you reach the length of h matrix. Then copy all the things you have found and assign that things to t matrix.


Strings are a relatively new development in MATLAB, actually. So if you have MATLAB version 2016b or later, you can run this code instead, and get the result you're looking for (it is identical to your code, but the single quotes are replaced with double quotes).

h = "wudh2h2";
w = "uwuuw";
v = [h w];
t = v(1);

However, most people are probably still running older versions of matlab, so it's better to create a cell array of character strings instead. This ensures that each string is preserved within the cells, and can be accessed without knowing the their lengths beforehand.

v = cell(2, 1)    % This creates a 2x1 cell array 
v{1} = 'wudh2h2';
v{2} = 'uwuuw';
t = v{1};

I guess to answer your question about why you can't implement it your way. MATLAB doesnt (before R2016b) have Strings the way other languages do. When you do something like h='wudh2h2';, you're actually creating a character array which looks like [w, u, d, h, 2, h, 2]. So when you concatenate the arrays by doing v = [h w], you're just creating a longer character array; the two original "strings" are no longer distinguishable. The line v(1) is simply calling the first element of your character array, which is the character w.

  • 1
    $\begingroup$ +1, I learned something from this. One of the reasons I dropped MATLAB was exactly this "MATLAB doesnt have [. . .] the way other languages do" and this is a huge waste of time when you are trying to solve a problem. $\endgroup$ – A_A Nov 14 '17 at 14:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.