Build a matrix where each column of the image is a single color

2 次查看(过去 30 天)
have a homework assignment that I just need help understanding. We are to make a 4x6x3 matrix, where each column of the image is a single color, in rainbow order (Red, Orange, Yellow, Green, Blue, Purple), but we must use for loops. I wrote this code, however, I'm not getting a rainbow? Can someone help me out?
mat=zeros(4,3,3);
row1=[255,0,0];
row2=[0,255,0];
row3=[0,0,255];
row4=[0,255,255];
row5=[255,0,0];
row6=[255,0,255];
mycolormap = reshape([row1;row2;row3], 1, 3, 3);
for i=1:4
mat(i,:,:)=mycolormap;
end
imagesc(mat);

回答(1 个)

Geoff Hayes
Geoff Hayes 2016-9-29
Sarah - what is your intent with the line of code
mycolormap = reshape([row1;row2;row3], 1, 3, 3);
where you only use the first three colours that you have defined and so the final image has only three colours in it? Also, I'm not sure why you call them rows when it is the columns that you want to colour. In fact, your for loop is iterating over each row and not each column. Remember that the second dimension corresponds to the column and so what you really want to do is
for k=1:size(mat,2) % 2 for the second dimension i.e. column
Defining the rainbow matrix is a good step, though you may want to define the data type as well as an 8-bit unsigned int
rainbowImg = zeros(4,6,3,'uint8');
Next, iterate over each column of the image and colour it appropriately
for k=1:size(rainbowImg,2)
if k==1
% red
rainbowImg(:,k,1) = 255;
elseif k==2
% orange - what is the RGB code for this colour?
% etc. for each column
end
end
Since this is homework, the above code should get you started with the first column. You would just need to do something similar for every other column. Note that there are other ways to do this too outside of using for loops.

Community Treasure Hunt

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

Start Hunting!

Translated by