Populate a 1000x1000 array with rows where a value is added every second, then third etc. column
10 次查看(过去 30 天)
显示 更早的评论
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!
采纳的回答
Jan
2022-4-28
编辑:Jan
2022-4-28
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 个)
DGM
2022-4-28
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!