0

I'm new in MATLAB and I have the following formula for the following problem. If I want to set a grey scale from 64 to 256, I just modify a matrix to create a M[256,3] where:

  1. M[Xi,1]=M[Xi,2]=M[xi,3]
  2. M[Xi,Yi] < M[Xi+1,Yi]
  3. M[1,Yi]=0
  4. M[256,Yi]=1.

So I need to create a matrix with steps that I don't know; the last element is 1 and the first is 0, I got the following formula that works with any column:

C[i]= X0 - (Xn*i -Xn)/N

where X0=0, Xn=1 and N=256.

with a loop like this:

k=(1:256);
for i=1:256,
   k(i)=(i-1)/255;

and then setting the values to the palette of colors

palette=zeros(256,3);

 for ii=1:3, 
     palette(:,ii)=k;
 end

Is there any other alternative to do is? It is really annoying using that much loops for something I think MATLAB must have: seting the values to an array based on the first element, the last element and the size of the vector.

Divakar
  • 218,885
  • 19
  • 262
  • 358
Luis Rubiera
  • 17
  • 1
  • 6

3 Answers3

3

Let's bsxfun -

palette = bsxfun(@rdivide,[0:255]',255*ones(1,3))

Explanation : Here's how one can deduce the bsxfun solution starting from your original loopy approach :

1) Setup 1D Array of i values -

I=(1:256)-1 

2) Store divisor of 255 as a row vector of 3 such elements corresponding to three columns of desired output -

D = 255*ones(1,3)

3) Finally, perform elementwise division of I by D after transposing I to give us our desired output -

out = bsxfun(@rdivide,I.',D)
Divakar
  • 218,885
  • 19
  • 262
  • 358
2

You first need a vector of equidistant steps from X0 to Xn, with a total number of N points. Exactly this can be achieved with

linspace(X0,Xn,N)

(note that this is a row vector, i.e. its size is [1 N]). The simplest way of repeating this 3 times is the repmat function, which repeats its first argument in a way specified by its second argument, so

repmat(linspace(X0,Xn,N)',[1 3])

will repeat linspace(X0,Xn,N)' (a row vector, of size [N 1]) three times columnwise, creating exactly the matrix (of size [N 3]) you need.

Note that as @Divakar points out in the comments to his answer, the proper way to transpose is by linspace(X0,Xn,N).', as .' is the transpose operator. Using simply ' will compute the conjugate transpose, but as long as you're working with real numbers the two are identical (but it's easy to forget about .' if once you actually want to just transpose a complex variable).

Community
  • 1
  • 1
2

The gray function does that:

palette = gray(256);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147