Clear Filters
Clear Filters

function for if loop

2 views (last 30 days)
Kacper Witasinski
Kacper Witasinski on 19 Feb 2022
Answered: Voss on 19 Feb 2022
Hello guys,
I would like to create a function that I could use it in elsewhere script in the future. Here is what I've came up with:
function output = name()
output = [?????? ??????]
for k = 1:size(table)
if table.("My Column1")(k) == "Manchester City"
ChampionsYears(k) = 2012;
elseif table.("My Column2")(k) = "Manchester City"
ChampionYears(k) = 2012;
end
.
.
.
end
end
I have table with 10 columns, and I want the function (and loop) to check through the table (row-wise) if any string in the cell is "Manchester".
If so, assign the value of 2012 to "Champion Years". I want the function to have no inputs, and to be like so: displayed message (any) in command window and assign value of 2012 to Champion Years. Could you please modify this piece of code?
Regards

Accepted Answer

Voss
Voss on 19 Feb 2022
name(); % call the function defined below, as specified
My_Column1 My_Column2 My_Column3 My_Column4 My_Column5 My_Column6 My_Column7 My_Column8 My_Column9 My_Column10 __________ _________________ __________ __________ ____________ _________________ __________ ______________ _________________ _________________ "" "Manchester City" "" "" "" "Manchester City" "" "" "" "" "" "" "" "" "" "Manchester City" "" "" "" "" "" "" "" "" "" "" "" "Pasadena, CA" "" "" "" "" "" "" "Austin, TX" "" "" "" "Manchester City" "" "" "" "" "" "" "" "" "" "" "Manchester City" 2012 2012 NaN 2012 2012
function name() % no input, as specified, and no output
% table has to come from somehwere (can't be an input), so I make one up
% here. yours may be loaded from a file or whatever.
% table of empty strings with 5 rows and 10 columns:
my_table = cell2table(repmat({""},5,10),'VariableNames',sprintfc('My_Column%d',1:10));
% put some non-empty strings in some cells of the table:
my_table{1,2} = "Manchester City";
my_table{1,6} = "Manchester City";
my_table{2,6} = "Manchester City";
my_table{3,8} = "Pasadena, CA";
my_table{4,5} = "Austin, TX";
my_table{4,9} = "Manchester City";
my_table{5,10} = "Manchester City";
% display table for visual reference:
disp(my_table);
% build ChampionYears column vector, which is 2012 when any cell in
% the corresponding row of my_table is "Manchester City" and NaN otherwise:
ChampionYears = NaN(size(my_table,1),1);
for k = 1:size(my_table,1)
if any(my_table{k,:} == "Manchester City")
ChampionYears(k) = 2012;
end
end
% display ChampionYears to command line:
disp(ChampionYears);
end

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!