2

I want to create a container (array, vector, ... I don't perfectly know the difference between these in Matlab) of strings. I want to use it for display purposes and printing to files mainly. In C++ I would have something like:

std::vector<std::string> str;
str.push_back( "Test1" );
str.push_back( "Test2" );
str.push_back( "Test3" );

for( unsigned int i = 0; i < str.size(); i++ )
{
    printf( "%s\n", str[i].c_str() );
}

My question being: How can I achieve something similar in Matlab, or is it even possible. I've tried a few things I've found here and there but nothing works. Here are the things I tried:

str = ['Test1' 'Test2' 'Test3'];

str = ['Test1', 'Test2', 'Test3'];

str = ['Test1'; 'Test2'; 'Test3'];

2 Answers 2

5

Use { and } (cell arrays), otherwise you'll just concatenate strings.

str = {'test1', 'test2', 'LongerTestString'};

for ii = 1:length(str);
    disp(str{ii});
end
Sign up to request clarification or add additional context in comments.

3 Comments

strings are arrays of characters, a cell array can contain multiple arrays (of different length), thus it can contain multiple strings. A matrix can also contain strings (of the same length) in its rows/columns, but a cell array is much better suited imo.
@GuntherStruyf I have adapted my answer to illustrate that.
yeah, the answer is fine, I just wanted to explain how the data is stored and what the options are when working with strings/characters.
0

A complement to Nick answer (because cellfun are fun :)):

str = {'test1', 'test2', 'LongerTestString'};
cellfun(@disp, str)

1 Comment

I agree with you that they are fun, however they can be hard to debug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.