MATLAB: Reshape matrix adding columns of zeros at specific index

columnsMATLABreshape

Hello,
I am a beginner in Matlab and right I am a bit stack in a part of my code. The code import a baseline txt. file data that contain variables from combustion engine. The baseline has A=4×178 first row name of variables and the other three numbers.
The thing is that after a time (project duration) the number of variables is increased (new variables are added) and now I have a txt files composed by B=4X204 with 26 new variables.
Without enter in detail the script to export the txt. file in the right format, what I have got is a vector of index of which new variables in B are not in A.
Now, what I am try to do is reshape A to be the same size than B but with zeros columns at the specific index.
I would be really grateful whether somenone could point me out in the right direction.
Thank you very much in advanced.
if Start_comparison==0
if columns_baseline<columns_logs
index_new=~ismember(Variables_Logs,Variables_Baseline);
Numeric_index=find(double(index_new));
end
end

Best Answer

The simplest way to do what you want is to import the files as tables and let matlab do all the work of figuring out the format and missing columns for you. readtable with the correct import option can do it all. Interestingly, testing with your files let me find some strange quirks of readtable that I'll be reporting shortly to Mathworks.
Note that your demo files have a tab character at the end of each line. That's not normal and even in excel results in an extra column of data imported. You ought to fix your export code from puma. i assume it's not written by AVL. Thankfully, we can tell matlab not to import that last empty column.
I'm not reproducing the UI part of your code, the rest can be replaced by:
%these three comes from UI
path = pwd;
Baseline_TXT = 'Baseline.txt';
Log_TXT = 'Logs.Txt'
%import code
opts = detectImportOptions(fullfile(path, Log_TXT)); %detect format of text file
opts.ExtraColumnsRule = 'ignore'; %to ignore extra tab at the end of lines. Otherwise, default rule of 'addVars' would add an extra variable
%default of opts.MissingRule is 'fill' which is exactly what we want. Missing columns will be filled by FillValue (NaN by default)
%We could tell matlab to import the 2nd line as units. However, there's a quirk where it doesn't work with missing variables. Not critical anyway
%opts.VariableUnitsLine = 2; %bug!
log = readtable(fullfile(path, Log_TXT), opts);
baseline = readtable(fullfile(path, Baseline_TXT), opts);
Since I'm using the import options of the log file for loading the baseline. It uses all the variable defined in the log file, and if not present fill them with NaN because of the default 'fill' value of MissingRule. As you can see in just 4 lines, everything is done.