Dymaxion Fuller
Dymaxion Fuller

Reputation: 105

Remove Rows from Matrix and Shift

I found some information online but not enough to help me solve this issue. I am looping through multiple files and extracting data from the files. It is then stored in an array called extract. The problem is that I am doing it in for loop and looking for a certain string. If the string does not exist, it still iterates through the loop and increases my counter. So, if I loop through two files and the string I am looking for is not there, but on the third one it is there, then the first row I write to is row 3 and not row 1. I have also attached an image of the first few data elements. I would like to be able to delete the rows that have [] and then shift the rows below up. Here is the code and thank you for your time. If there is anything else I can provide please let me know!

        function this = extractData(this, xAxis, yAxis)
        s = dir('*.txt'); % Gather all text files

        for i=1:length(s) % Loop through and gather data until last element of strcuct
            j = 1;
            fid = s(i).name; % Open file in read-only mode
            this = this.readDataFromFile(fid);
            if ~contains(this.metaData(:,1), xAxis)
                continue;
            end
            x = this.metaData(find(contains(this.metaData(:,1), xAxis)),3);
            this.extract{i,j} = x;
            j = j+1;
            y = this.metaData(find(contains(this.metaData, yAxis)),3); %#ok<*FNDSB>
            this.extract(i,j) = y;
        end %for

        xAxis = strrep(xAxis, ' ', '_'); % For file formatting
        yAxis = strrep(yAxis, ' ', '_');
        this.colLabels = {xAxis, yAxis};

        % Write it all to a file 
       fileName = 'myTestFile.txt'
       filepath = cd;
       file = fullfile(filepath, fileName);
       fid = fopen(file, 'w');
       if fid == -1
           error ('Cannot open file for writing: %s', file);
       end

       % File must denote where meta-data and data begin
       fprintf(fid, '%-72s', '=============================meta data============================='); 
       fprintf(fid, '\n');
       for row=1:size(this.extract,1)
           for col=1:size(this.extract,2)
                fprintf(fid, '%s', this.extract{row,col});
           end
           fprintf(fid, '\n');
       end %for
        fclose(fid);               
    end %extractData            

enter image description here

Upvotes: 0

Views: 49

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60780

Are you looking for a loop logic like this?

k = 1;
for i=1:length(s)
    fid = s(i).name;
    %...
    if %...
        continue;
    end
    this.extract{k,j} = %...
    k = k + 1;
end

Here we're simply decoupling the index i that indicates which file to read from, from the index k that indicates which row in the output matrix to write to.

Upvotes: 1

Related Questions