Reputation: 11
I'm trying to create a matrix in MATLAB.
The matrix goes from 255 to 0 from left to right as well as from top to bottom. That is, the top left corner is the only place the matrix has a value of 255, and the farthest right column as well as the very bottom row have values of 0.
I'm trying to do this without using any loops, any ideas?
Upvotes: 1
Views: 94
Reputation: 15867
Here is a solution using bsxfun
and min
:
a = 255:-1:0;
result = bsxfun(@min, a, a.');
As of MATLAB r2016b you can write:
result = min(a, a.');
For a maximum value of 3
this output will be generated:
result =
3 2 1 0
2 2 1 0
1 1 1 0
0 0 0 0
Upvotes: 1
Reputation: 30101
You can do this in one operation using hankel
M = hankel(255:-1:0, zeros(1, 256));
Output on a smaller example:
n = 3; % Top left value
M = hankel(n:-1:0, zeros(1, n+1))
>> M = [ 3 2 1 0
2 1 0 0
1 0 0 0
0 0 0 0 ]
Another useful function for constructions like this is toeplitz
. The same result can be generated:
M = fliplr(toeplitz(zeros(1, 256), 0:255));
Upvotes: 0
Reputation: 899
Based on the answer found here: circle with gradient gray scale
One possible solution would be:
N = 255; %// this decides the size of image
[X,Y] = meshgrid(1:-1/N:0, 1:-1/N:0) ;
out= X + Y-1;
out(out<0)=0;
out=uint8(out*255);
Upvotes: 0