For loop doesn't doesn't summate

2 views (last 30 days)
GG
GG on 28 Nov 2021
Edited: Image Analyst on 28 Nov 2021
Month and data are imported tables. n==1 means that it is January, the purpose is to add to "number" with a value corresponding to the month but when I run I still get number=0. What is wrong with this code?
number=0;
for n=Month
if n==1
number=number+data(n);
end
end

Accepted Answer

Image Analyst
Image Analyst on 28 Nov 2021
Edited: Image Analyst on 28 Nov 2021
number is overwritten every iteration so it will take on only the value from the last iteration. If it's zero at the end then data(Month(end)) must have been -1. To not overwrite, do
number = data; % Initilize number;
% Find out what indices have data == 1.
valueIs1 = Month == 1;
number(valueIs1) = 2; % Add 1 to all indices where value is 1, which makes them 2.
If you need help, attach Month and data
save('Answers.mat', 'Month', 'data');
Use the paperclip icon to attach the .mat file.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by