I want to add this cell variable 'condition_col' to existing matrix 'data' if certain conditions are met, following code doesn't work, any help?

condition_col = 'codition1'
condition_col = cellstr(condition_col);
data = num2cell(data);
for i = 1:length(data)
if strcmpi(data(i,5),1) && data(i,6)> 5 && strcmpi(data(i,5), 2) && data(i,6) < 5
data{i} = [data, condition_col];
end
end

3 commentaires

try making your data a "table" instead of a "cell" & assign column names to the table
following code doesn't work, any help
The code makes no sense at all and there's no comment explaining what it's meant to do.
Can you explain with examples using valid matlab syntax what it is you want to do?
I just want to add a new variable to one column in it's each row when a certain conditon is met. For example:
if col5(1,1)==1 && col6 <5
%then add variable1 in the corresponding row to col10
elseif col5(1,1)==2 && col6 >5
%then add variable2 in the corresponding row to col10
end

Connectez-vous pour commenter.

 Réponse acceptée

See if this helps to get you on the right track:
% set up dummy data to work with
data = rand(20,1);
data = array2table(data);
data.Properties.VariableNames = {'MyColumnName'};
for ii = 1 : height(data)
% example condition, use your condition instead
if data.MyColumnName(ii) < 0.5
data.codition1{ii} = 'Condition Met';
else
data.codition1{ii} = '';
end
end

4 commentaires

I have no idea if that's what the OP wanted to do or not. If it is, I would recommend using categorical or logical instead of char vectors to indicate if the condition is met.
Note that, as usual in matlab, the loop is unnecessary
data.codition = repmat({''}, height(data), 1);
data.codition(data.MycolumnName < 0.5) = {'Condition Met'};
or better using categorical:
data.codition = categorical(data.MycolumnName < 0.5, [true, false], {'Met', 'Not Met'});
or simply using logical:
data.codition = data.MycolumnName < 0.5;
This worked for me; without making any loop
Thanks a lot.
Thanks Guillaume, that is a much better approach. Maybe you should write it up as a separate answer so the OP can accept it as the correct answer.
I'm fine with you getting the credit. You understood what the OP was asking for and got him in the right direction.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by