Populate a 1000x1000 array with rows where a value is added every second, then third etc. column

1 view (last 30 days)
CaraAkame
CaraAkame on 28 Apr 2022
Edited: dpb on 28 Apr 2022
I know how to make the individual rows:
% two = zeros (1,1000);
% two (2:2:end)=1;
and so on, but I can't do this for every row (this might be a roundabout way of doing it). How do I incorporate this in a loop? Preferably directly into an array. I've been trying for hours, but I haven't used matlab in years and was never the best at using it beyond graphs.
The array should look something like this:
1 1 1 1 1 1 1 1 1 1
0 1 0 1 0 1 0 1 0 1
0 0 1 0 0 1 0 0 1 0
0 0 0 1 0 0 0 1 0 0
(but for 1000x1000)
I somehow always end up with my array being just 1s when I try to incorporate it in a loop.
I've been trying to do some puzzles to get back into using matlab, and I managed fine for one that needed similar things, but with if/else; but for loops (which I think I need here) were always my kryptonite, so please help me! Thank you!
  4 Comments

Sign in to comment.

Accepted Answer

Jan
Jan on 28 Apr 2022
Edited: Jan on 28 Apr 2022
You want an output of size 1000x1000:
M = zeros(1000, 1000);
You want a loop to go from 1 to 1000:
for k = 1:1000
...
end
You want to set some elements to 1 in the k'th row of M:
M(k, a:b:c) = 1;
Here c is obviously 1000. Just find matching values for a and b.
You find an exhaustive tutorial here:
  1 Comment
CaraAkame
CaraAkame on 28 Apr 2022
Thank you!
This was really helpful in understanding what my mistake was, since I did most of that (forgot the k), and overcomplicated other stuff (the k again), on instinct and half remembered coding sessions from uni, and could not figure out why it wasn't working. Thank you for taking the time to explain this in steps!

Sign in to comment.

More Answers (1)

DGM
DGM on 28 Apr 2022
If you were getting a bunch of ones, you were probably pretty close.
N = 1000;
everyN = zeros(N);
for n = 1:N
everyN(n,n:n:end) = 1;
end
If you forgot the row index, the first pass would have set the entire array to 1.
  1 Comment
CaraAkame
CaraAkame on 28 Apr 2022
Oh wow, that looks very similar to what I did the first time around, I'm going to go try that right now. If I was really that close for the last few hours I'm going to be both proud and annoyed at myself!
.
.
It really was my biggest error. I mean, my starting statement for the for loop was also slightly wonky, but I'm sure I had the statement that way as well at some point as well. Thank you so much!

Sign in to comment.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!