How do I set every other number in an array to a specific number with one line?
53 views (last 30 days)
Show older comments
I'm trying to set every other element within an 5x5 array to 100 (so (1,1) (1,3) (1,5) ETC.) Within a single line of code. Im not sure how to do this, please help!
0 Comments
Accepted Answer
Stephen23
on 12 Jan 2018
>> M = zeros(5);
>> M(1:2:end) = 100
M =
100 0 100 0 100
0 100 0 100 0
100 0 100 0 100
0 100 0 100 0
100 0 100 0 100
1 Comment
More Answers (1)
Jan
on 12 Jan 2018
Edited: Jan
on 17 Oct 2020
See Stephen's answer, if you need the checkerboard distribution for an odd number of elements only. If the matrix can have even or odd number of rows and columns:
n = 5;
v = rem(1:n, 2);
M = (v.' == v) * 100; % Auto-expand, needs Matlab >= R2016b
With older Matlab versions:
M = bsxfun(@eq, v.', v) * 100;
EDITED: Less multiplications and therefore slightly faster:
n = 5;
v = rem(1:n, 2);
M = v.' .* (v * 100); % Auto-expand, needs Matlab >= R2016b
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!