Search code examples
stringmatlabreplaceexport-to-csvcell-array

Rearranging Cell array containing strings


enter image description here

The contents in the cell array are as in the image showed above. I have two issues:

  1. I have to move cells in columns to the preceding ones wherever there are 0s. For example in row 1, the 1x7 cell has to come to the cell after 1x19 cell and so on.

  2. While doing this, the cells with [] should also be moved replacing the preceding 0s.

I tried using strncmp, ismember and other functions, but the 0 is throwing errors.

UPDATE with working code

The code is this:

It doesnt do all the work though. The cells being copied have to be deleted from the end.

for m=1:200
for i=1:46
    for j=1:199

        try
            if(tags{i,j}==0)
                for k=j:199
                    tags{i,k}=tags{i,k+1};
                    tags{i,k+1}='';
                end
            end
        catch exception

        end
    end
end
end

EDIT - Question's part 2 : Not solved yet

Each of the cells contains strings. Is there any way I can write them to a text file? All the strings in a cell have to be in the same line followed by a new line for the strings in the next cell.

Again, I tried this using a lot of functions, but I am unable to do it properly. I just get the first string in every cell to the text file.


Solution

  • Here's an alternative approach: Instead of iterating over the array, create a new one and fill in only the non-zero values (note: if you want to avoid making a new array, you can, in the loop, create a temporary copy of the row, empty the row in the array, and overwrite). With some clever array shuffling, you could do step 3 without the loop entirely, btw.

    %# step 1: find non-zeros
    nonZeros = cellfun(@(x) ~iscell(x) && ~isempty(x), tags);
    
    %# step 2: create new array with all empty
    [nRows,nCols] = size(tags);
    newTags = cell(nRows,nCols);
    
    %# step 3: for every row: copy the non-zero entries
    [goodRows,goodCols] = find(nonZeros);
    
    for iRow = 1:nCols;
        myGoodCols = goodCols(goodRows==iRow);
        nGoodCols = length(myGoodCols);
        if nGoodCols > 0 && nGoodCols < nCols
           %# shift everything
           newTags(iRow, 1:nGoodCols) = tags(iRow,myGoodCols);
        end
    end
    
    %# step 4 : write out tags
    fid = fopen('tags.txt','w+');
    for iRow = 1:nRows
        for iCol = 1:nCols
            if ~isempty(tags{iRow,iCol})
            fprintf(fid,'row %i col%i : ',iRow,iCol);
            fprintf(fid,'%s ',tags{iRow,iCol}{:});
            fprintf(fid,'\n');
            end
        end
    end