Search code examples
matlabrubiks-cubemupad

Making a Rubik's Cube in Matlab?


I am trying to make a 3d model of Rubik's cube.

I initially tried it using the patch command

vert = [0 0 0; 0 1 0; 1 1 0; 1 0 0 ; ...
        0 0 1;0 1 1; 1 1 1;1 0 1];
fac = [1 2 3 4; ...
    2 6 7 3; ...
    4 3 7 8; ...
    1 5 8 4; ...
    1 2 6 5; ...
    5 6 7 8];
k = patch('Faces',fac,'Vertices',vert,'FaceColor','r');  % patch function
material shiny;
alpha('color');
alphamap('rampdown');
view(30,30); 

But since I may need to give different color to each surface I had to use the patch command multiple twice. Hence I was not able to refer the entire cube when I wanted to

Another method I found was using the command plot::Box in MuPAD

plot(plot::Box(0..1, 0..1, 0..1, Filled = TRUE,
               FillColor = RGB::Red),
     plot::Box(1..2, 0..1, 0..1, Filled = TRUE,
               FillColor = RGB::Red),
plot::Box(2..3, 0..1, 0..1, Filled = TRUE,
               FillColor = RGB::Red),
     plot::Box(0..1, 1..2, 0..1, Filled = TRUE,
               FillColor = RGB::Red),
plot::Box(0..1, 2..3, 0..1, Filled = TRUE,
               FillColor = RGB::Red),
     plot::Box(2..3, 1..2, 0..1, Filled = TRUE,
               FillColor = RGB::Red),
plot::Box(1..2, 2..3, 0..1,Filled = TRUE,
               FillColor = RGB::Red),
     plot::Box(2..3, 2..3, 0..1, Filled = TRUE,
               FillColor = RGB::RED,),
     Axes = None, Scaling = Constrained)

But here I am not able to give separate color to each surface. I tried using FillColorDirection = [0, 0, 1]) but it is not working

Is it possible to give separate color for each face when using the plot:Box or is there a better way of doing this?


Solution

  • I was able to solve the problem by using the patch itself. There is a property known as FaceVertexCData for patch. Through that we would be able to specify the color for each face. We should also Facecolor to flat as shown below

    cube = patch('Faces',fac,'Vertices',vertice,'FaceVertexCData',color,'FaceColor','flat');  % patch function
    

    In the above the color is 6*3 matrix in which each row has the RGB value of the color required. The color in each row is applied to faces in the order in which it was defined.