2
votes

Inside a loop I am generating an output (e.g., outputLine) which I wish to accumulate/add to a cell array.

Therefore, I am using this small snippet:

for...
    outputLine=strcat(FileName,',',coordString);
    outputTable=vertcat(outputTable,outputLine);
end

I get the obvious error as outputTable is not declared and if I add at the beginning of the script outputTable=' ';

I get this error “Dimensions of matrices being concatenated are not consistent.”

How can I accumulate the output in a cell array?

1
Try outputTable={} before the loop. Also, you can replace vertcat with {;} e.g. outputTable={outputTable;outputLine};Dan
Thanks. outputTable={} works fine but only with the vertcat.hs100
To concatenate two cells, [] has to be used, {} creates a nested cell.Daniel
In this case, I would use append : outTable{end+1}=outputLine Daniel

1 Answers

0
votes

The reason you are getting the error is that strings are arrays of type char. If you want to concatenate strings vertically, they have to be the same length to make up a proper char matrix, just like arrays of any other type.

You may want to read the Mathworks pages on how to index cell arrays as well as how to combine cell arrays.

There are a few of ways to append to your cell array. First off, the array has to be defined as a cell array. If you know how big it is going to be (which is the preferable case), before the loop, do

outputTable = cell(N, 1);

Otherwise, you will have to reallocate the array every time

outputTable = {}

For the case where the size is known,

outputTable{i} = outputLine;

Here i would be the index in the for loop or an external counter that you initialize before the loop and increment whenever you make an assignment. This will also work if you do not know the size of the list up front, but not as efficiently.

For the case where you just want to append to the list, do

outputTable = [outputTable; outputLine]

The notation [;] is syntactic sugar for vertcat, which you can use explicitly:

outputTable = vertcat(outputTable, outputLine)