MATLAB: How to join text in a table cell

concatenatehelpMATLABtable

Dear All,
This seems very simple but it is puzzling me.
I have a table that is called..well Table, I have attached a screenshot of it. The table is (69 by 5), I added an empty column called "Warning" to let me know if if any of the years exceed a specific threshold and if they do in which category of the letters.
So here is what I did:
Matrix = table2array(Table); % converted my Table into an array, Matrix is 69 by 4
v= {[],[],'M', 'X', 'N'};
%Adding the column of warning
emptyCol = cell(length(Years),1);
Table = [ table(emptyCol,'VariableNames', {'Warning'}) Table];
% Setting the threshold, if any values in columns M, X and N exceed 100, then the Warning column contains the letter
for i = 2:5
for d = 1:length(Years)
if ((Matrix(d,i))> 100 == 1);
Table.Warning(d)= v(i+1);
end
end
end
My problem is that if I run the code with values that exceed the threshold in columns M, X and N, I only get for N. what I mean is that the letters get over written I cant seem to have all three together like 'M','N','X' instead of just N. I tried to use strcat but nothing happens, it's either I am using it wrong or it's not what I should use for this case.
If you have any ideas on how I can overcome this please let me know.
Thank you,
M

Best Answer

Your whole process of adding a new column and detecting your excess threshold is overly complicated. There is certainly never any need to convert to a matrix.
%demo/test data
Table = array2table(randi([0 150], 69, 4), 'VariableNames', {'something', 'W', 'X', 'N'})
colnames = Table.Properties.VariableNames(2:4); %asumming you only want to test column 2:4
warnings = rowfun(@(val) {strjoin(colnames(val > 100), ',')}, ...
Table, ...
'InputVariables', 2:4, ...
'OutputVariableNames', 'Warning', ...
'SeparateInputs', false);
Table = [warnings, Table]
I've separated the rowfun call onto several lines for readability.
In the above, I call rowfun to process each row one at a time. 'InputVariables' tells it which columns to process (2 to 4), 'OutputVariableNames' tells it which name to give to the output column, 'SeparateInputs', false tells it to keep the values of columns 2:4 together as a vector (easier to process).
The processing function I'm giving to rowfun is an anonymous function which one input val. That val will receive columns 2:4 of each row as a vector. I compare the values of this vector to your threshold. This gives me a logical vector that is used to filter the columns names. I then join these filtered column names together into one char array with strjoin and finally wrap that into a cell array so that it can be put into a table column.
P.S: Please give a better name to your table and to columns M, X, N. Something that actually explain what's in there. Yearlysomething would be a better name for the table, whatever that something is.