Clear Filters
Clear Filters

Using a loop for repeating steps

3 views (last 30 days)
Anonymous Matrix
Anonymous Matrix on 21 Feb 2017
Edited: Jan on 21 Feb 2017
I need some help with a loop. i have codes here:
RandomArray= randi([-100 100],20,5); % step 1
RandomArray=sort(RandomArray(:)); % step 2
RandomArray = reshape(RandomArray,5,20).';
y=mean(RandomArray,2); % step 3
[c,index] = min(abs(y-0)); % determines which row is closest to 0
RowNumber= index;
I have to repeat these steps 1000 times then plot RowNumber in a histogram. I know I can use a FOR loop but i'm a bit lost on how to assign the codes. Can someone help? please and thank you.
  4 Comments
Akira Agata
Akira Agata on 21 Feb 2017
Is this what you want to do?
N = 1000;
RowNumber = zeros(N,1);
for kk=1:N
RandomArray= randi([-100 100],20,5); % step 1
RandomArray=sort(RandomArray(:)); % step 2
RandomArray = reshape(RandomArray,5,20).';
y=mean(RandomArray,2); % step 3
[c,index] = min(abs(y-0));
RowNumber(kk) = index;
end
% Plot histogram
histogram(RowNumber);
Anonymous Matrix
Anonymous Matrix on 21 Feb 2017
Yes! i was mainly lost on where to put the kk. thanks!

Sign in to comment.

Answers (1)

Akira Agata
Akira Agata on 21 Feb 2017
Just in case, let me copy&paste my comment to the answer section.
N = 1000;
RowNumber = zeros(N,1);
for kk=1:N
RandomArray= randi([-100 100],20,5); % step 1
RandomArray=sort(RandomArray(:)); % step 2
RandomArray = reshape(RandomArray,5,20).';
y=mean(RandomArray,2); % step 3
[c,index] = min(abs(y-0));
RowNumber(kk) = index;
end
% Plot histogram
histogram(RowNumber);
  1 Comment
Jan
Jan on 21 Feb 2017
Edited: Jan on 21 Feb 2017
+1. Omit the funny "-0" from min(abs(y-0)).

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!