Using an if/else statement inside of a for loop

98 ビュー (過去 30 日間)
Amanda Wojcik
Amanda Wojcik 2017 年 11 月 1 日
コメント済み: Walter Roberson 2020 年 6 月 29 日
Hi! I am trying to write an if else statement inside of a for loop in order to determine how many people surveyed had a specific response. I posted my code below. Every time I run it instead of generating the numbers, it generates my fprintf statement that amount of time. I am just really confused because I followed the template my professor gave and it just isn't working for me. Thank you,
y=load('Class19_survey.txt');
ag=0;
ne=0;
dis=0;
for k=1:length(y)
if y(k)>=4
ag=ag+1;
fprintf('\nThe number of people who agree is\n',ag)
elseif y(k)==3
ne=ne+1
fprintf('\nThe number of neutral responses is\n',ne)
else y(k)<=2
dis=dis+1
fprintf('\nThe number of disagree responses is\n', dis)
end
end
  1 件のコメント
Amanda Wojcik
Amanda Wojcik 2017 年 11 月 1 日
Sorry here is an easier version to read
y=load('Class19_survey.txt');
ag=0;
ne=0;
dis=0;
for k=1:length(y)
if y(k)>=4
ag=ag+1;
fprintf('\nThe number of people who agree is\n',ag)
elseif y(k)==3
ne=ne+1
fprintf('\nThe number of neutral responses is\n',ne)
else y(k)<=2
dis=dis+1
fprintf('\nThe number of disagree responses is\n', dis)
end
end

サインインしてコメントする。

採用された回答

KL
KL 2017 年 11 月 1 日
Perhaps you want something like this,
y=load('Class19_survey.txt');
ag=0;
ne=0;
dis=0;
for k=1:length(y)
if y(k)>=4
ag=ag+1;
elseif y(k)==3
ne=ne+1;
else y(k)<=2
dis=dis+1;
end
end
fprintf('\nThe number of people who agree is\n',ag)
fprintf('\nThe number of neutral responses is\n',ne)
fprintf('\nThe number of disagree responses is\n', dis)
but you could also do it without the loop and if statements,
ag = length(y(y>=4));
ne = length(y(y==3));
dis = length(y(y<=2));
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 6 月 29 日
ag = nnz(y>=4);
ne = nnz(y==3);
dis = nnz(y<=2);

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 11 月 1 日
y=load('Class19_survey.txt');
ag=0;
ne=0;
dis=0;
for k=1:length(y)
if y(k)>=4
ag=ag+1;
elseif y(k)==3
ne=ne+1;
else y(k)<=2
dis=dis+1;
end
end
fprintf('\nThe number of people who agree is\n',ag);
fprintf('\nThe number of neutral responses is\n',ne);
fprintf('\nThe number of disagree responses is\n', dis);

カテゴリ

Help Center および File ExchangeLanguage Fundamentals についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by