Search code examples
matlabreadfile

Matlab: Read a certain file and make a calculation on columns


I have file names go on 2.txt 4.txt 8.txt 12.txt 14.txt. And each file structure looks like

enter image description here

I want to read each designated file and do some calculations with the designated columns for instance, after calling 2.txt file I want to calculate column(A)+column(I)

The questions

  1. How can I call the certain file with their name
  2. How can I do calculations with this file columns

Here is my code

function[t]=ad(x)
    folderName='C:\Users\zeldagrey6\Desktop\AD';
    fileinfo=dir([folderName filesep '**/*.txt'] );
    filename={fileinfo.name};
    fullFileName=[folderName filesep filename{x}];
    d=readtable(fullFileName, 'ReadVariableNames', true);
    t=d.A+d.I;
end

The problems of the code

  1. When I put ad(2) into array i call 4.txt instead of 2.txt. I guess it does not care the names of the text just read them according to their sequence

  2. Is there any way to assign with each column like var1,var2 and do some calculations with var1+var2 instead of d.A+d.I


Solution

  • yes, you can refer to table contents with curly brackets like this:

    A = (30.1:0.1:30.5)';
    I = (324:328)';
    Angle = (35:5:55)';
    FWHM = (0.2:0.05:0.4)';
    d = table(A,I,Angle,FWHM);
    t1 = d.A + d.I;
    t2 = d{:,1} + d{:,2};
    

    See that t1 and t2 are equal