Finding sum of a loop
Show older comments
Hi, I'm new to matlab and was wondering how one would calculate/ code for the total sum? I've attached what I've been experimenting with below. Thanks!
%Homework 1 Basic question 4
for i = 1:10
A=(1:1000); %chronological count from 1 to 1,000
b=randi([1,1000],1,40); %to randomize set
c=max(b); %the maximum value amount
d= ((40+1)/40)*c-1 %to bore an estimated output
end
1 Comment
Image Analyst
on 13 Sep 2018
What exactly do you want ot sum? All the d's? The b's or c's, or all of them? What is the purpose of A which is assigned but never used? Did you want to sum the values of A at the locations defined by b? Please clarify.
Answers (1)
You should always preallocate the output arrays before the for loop, which will have two benefits:
- improve efficiency.
- remove any errors and bugs due to an existing variable having the same name.
N = 10;
A = 1:1000;
d = nan(1,N); % preallocate
for k = 1:N
b = randi([1,1000],1,40); %to randomize set
c = max(b); %the maximum value amount
d(k) = ((40+1)/40)*c-1; %to bore an estimated output
end
sum(d)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!