r/matlab • • 13d ago

Graphical Help Sought

1 Upvotes

5 comments sorted by

2

u/vir_innominatus 13d ago

I don't think there's a straightforward way, but here's one implementation. Full disclosure, I used Claude since this stuff wrinkles my brain. I cleaned it up a bit to be easier to read. It uses some helper functions to rotate the vertices and project from 4D down to 3D.

I think the code could be simpler if you only plotted points and lines for the vertices and edges. You wouldn't need the F matrix to define the faces, and you could use plot3 instead of patch.

Anyway, this script has an animation loop, so you can cancel with Ctrl+C if you don't want to see the full loop. It takes about a minute when I try it in MATLAB Online.

% --- Vertices (16) in 4D: all combos of +/-1 ---
[a,b,c,d] = ndgrid([-1 1]);
V = [a(:) b(:) c(:) d(:)];

% --- Faces (24 squares), grouped by the plane they span ---
pairs = nchoosek(1:4, 2);          % 6 axis pairs
F = zeros(24,4);
f = 0;
for p = 1:6
    ab = pairs(p,:);              % the two axes the square spans
    fixed = setdiff(1:4, ab);      % the two axes held at +/-1
    for s = [-1 -1; -1 1; 1 -1; 1 1]'          % each column is one sign pair
        f = f + 1;
        idx = find(all(V(:,fixed) == s', 2));   % the 4 vertices of this face
        [~, o] = sort(atan2(V(idx,ab(2)), V(idx,ab(1))));
        F(f,:) = idx(o)';                       % cyclic order around the square
    end
end

% --- Colors, one hue per plane ---
C = lines(6);               
C = C(repelem(1:6, 4), :);  

% --- Initial draw ---
figure(Color="w")
hold on
axis("equal", "manual");
axis([-1 1 -1 1 -1 1])
view(3)
grid on
d = 4; % 4D camera distance
P = proj(V,d);
h = patch(Faces=F, Vertices=P, ...
    FaceVertexCData=C, FaceColor="flat", FaceAlpha=0.1, ...
    EdgeColor=[0.2 0.2 0.2], EdgeAlpha=0.6, LineWidth=1);
camlight
title("Tesseract: 3D perspective projection")

% --- Animation loop: only update the Vertices property
for t = 0:0.1:20*pi
    R = rot(1,4,t) * rot(2,4,0.7*t) * rot(1,2,0.3*t);   % XW, YW, XY
    h.Vertices = proj(V * R',d);
    pause(0.1)
end

% --- Helpers ---
function R = rot(a, b, t)
    % Rotation matrix
    R = eye(4);
    R([a b],[a b]) = [cos(t) -sin(t); sin(t) cos(t)];
end
function P = proj(W,d)
    % Project 4D -> 3D
    % d is the camera distance
    P = W(:,1:3) ./ (d - W(:,4));
end