For loop doesn't doesn't summate

1 visualizzazione (ultimi 30 giorni)
GG
GG il 28 Nov 2021
Modificato: Image Analyst il 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

Risposta accettata

Image Analyst
Image Analyst il 28 Nov 2021
Modificato: Image Analyst il 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.

Più risposte (0)

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by