Search code examples
matlabmatrixplotcell-arrayis-empty

Change empty matrices to zero matrices of the same dimensions in matlab


I'm relatively new to matlab, so this might be an easy question, which I apologize for.

I have a cell array with cells of various dimensions. Some are empty matrices (0x2 empty matrix, 0x3 empty matrix, 0x16 empty matrix...stuff like that), and some aren't empty matrices. I'm trying to plot the cell array like so:

for n = 1:numel(cellarray)
    plot(cellarray{1}(n))
    hold on
end

But because I have some empty matrices, I get an error message when I try to run this loop and plot.

Is there any way I can change the empty matrices in my cell array to zero matrices of the same dimensions so that I can plot it without an error message? Thanks so much for any and all help!


Solution

  • All your code is doing - or trying to do - is printing the n-th element of the first element of the cell array. Since the first element of the cell array contains fewer than n elements you get the error message you show in the comments.

    From your description is sounds as if you are expecting it to plot the n-th element of the cell array - which it is not doing.

    You most likely want,

    for n = 1:numel(cellarray)
        if ~isempty(cellarray{n})
            plot(cellarray{n})
            hold on
        end
    end