"vertcat" error with array of strings

11 views (last 30 days)
I have an array of strings, which is used to store a collection of filenames to retrieve data. Depending on the task at hand, sometimes I need to access the data from only certain files, in which case I would like to comment out some filenames from the array.
When I do that, I get an error saying:
Error using ==> vertcat
CAT arguments dimensions are not consistent.
Here's a test program that illustrates the problem:
fprintf('\n\n BEGIN \n\n');
input_file_array = {...
'test1.txt',...
'test2.txt', ...
%'test3.txt', ...
'test4.txt', ...
};
fprintf('\n\n DONE \n\n');
Note that I get the error only when there is a continuation of the array elements after the commented line (but if I were to comment out both test3 and test4, I get no error).
I'm using Matlab R2007a.

Accepted Answer

Walter Roberson
Walter Roberson on 2 Mar 2011
You can't do that. The commented out line is treated as a blank line, which switches over the parsing to vertical concatenation, the same as if you were using { 'test1.txt', ... 'test2.txt' 'test4.txt' }
which would be equivalent to trying to do
{ 'test1.txt', 'test2.txt'; 'test4.txt'}
What I suggest is that you switch over to vertical concatenation anyhow. Transpose the resulting cell array if you need to:
input_file_array = {...
'test1.txt';...
'test2.txt'; ...
%'test3.txt'; ...
'test4.txt'; ...
};
The % will be treated as a blank line with the implied vertical concatenation, but since you are using vertical concatenation anyhow you don't run in to a conflict.
You can simplify this code as:
input_file_array = {
'test1.txt'
'test2.txt'
%'test3.txt'
'test4.txt'
};
taking advantage of the implicit vertical concatenation.

More Answers (2)

Andrew Newell
Andrew Newell on 2 Mar 2011
That commented line is just like having an empty line in the middle of your command (try it!). You could do this:
input_file_array = {...
'test1.txt',...
'test2.txt', ... %'test3.txt', ...
'test4.txt', ...
};

Ksenia
Ksenia on 3 Mar 2011
Thank you all very much for your quick and insightful replies! Such an easy explanation (and solution) for something that has been bugging me for a long time.
Appreciate you help!

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!