MATLAB: Reassigning columns to a table

table

Hi,
I have a table A from which I selected few columns to recompute using function correctiona. The column names are from a survey and they are quite confusing sometimes but I want to retain how they were named.
B=[A.SQ013_SQ001,SQ013_SQ004,A.SQ013_SQ003,A.SQ013_SQ002,A.SQ013_SQ001,A.SQ013_SQ004,A.SQ013_SQ003,A.SQ013_SQ002];B_corrected=correctiona(B); %B_corrected is is the corrected B matrix
is their a way to reassign the values of B_corrected to the matrix A without having to write long codes like this:
A.SQ013_SQ001=B_corrected(:,1);
A.SQ013_SQ004=B_corrected(:,2); etc….
In other words, can I tell matlab that the each of B_corrected columns to be reassigned to Table A based on the names I used to construct B. The reason is that my correction codes ar every long and confusing and I am afraid of making mistakes. It would be easy if what I take from table A could be reassigned back without having to deal with the column names after each manipulation.

Best Answer

If you keep everything tables, you can use the VariableNames property to indicate which variables are being updated. MATLAB is able to align the variables by their names. See more on how ot access data in tables here.
% Create a table with 4 variables
SQ1 = (1:5)';
SQ2 = SQ1;
SQ3 = SQ1;
SQ4 = SQ1;
A = table(SQ1,SQ2,SQ3,SQ4)
A = 5x4 table
SQ1 SQ2 SQ3 SQ4 ___ ___ ___ ___ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5
% Create table B from 2 variables from table A
B = A(:,["SQ2","SQ4"]);
% Modify B
B_corrected = flipud(B)
B_corrected = 5x2 table
SQ2 SQ4 ___ ___ 5 5 4 4 3 3 2 2 1 1
% Use the variable names of B_corrected to replace the values in A
A(:,B_corrected.Properties.VariableNames)=B_corrected
A = 5x4 table
SQ1 SQ2 SQ3 SQ4 ___ ___ ___ ___ 1 5 1 5 2 4 2 4 3 3 3 3 4 2 4 2 5 1 5 1