Create an App to Explore 3‑D and 4‑D Medical Volumes with Synchronized Multi‑Panel Views
R2026bThis example shows how to build an app using App Designer to explore 3‑D and 4‑D medical image volumes with synchronized multi-panel views. Using the FourPanelMedicalViewerApp app, you can visualize a medical volume simultaneously in three orthogonal 2‑D slice views (transverse, sagittal, and coronal) and in a 3‑D volume rendering. The app supports both static 3‑D volumes and time‑varying 4‑D volumes, such as cardiac cine or dynamic contrast‑enhanced data. Using the app, users can perform these tasks:
Import medical volumes from files, folders, or PACS servers.
View simultaneous orthogonal slices (transverse, sagittal, coronal) with 3-D volume rendering.
Navigate through slices using interactive crosshairs synchronized across all views.
Switch between different 3-D rendering styles.
Play through 4-D time-series medical data with animation controls.
Manually navigate time-frames using a slider or previous and next buttons.
In this example, you first build reusable custom UI components you can use for importing data from a PACS server and for viewing slice stacks and multi‑panel medical volumes. Then, you build an app that integrates these components, provides volume import options, and adds interactive controls for 3‑D rendering and time‑series playback. You can reuse the custom UI components as standalone tools or in different apps to improve code reusability, logic isolation, and maintainability.
Open App Designer
App Designer is an interactive development environment for designing custom UI components and apps and programming their behavior.
To build the app from scratch, open App Designer using this command. Alternatively, you can open App Designer by selecting the Design Apps option on the Apps tab.
appdesigner
In this example, you build the FourPanelMedicalViewer and ImageStackScrubber custom UI components, the PACSConfigManager custom class, the PACSConnectionApp app, and the FourPanelMedicalViewerApp app. The custom UI components, the PACSConnectionApp app, the PACSConfigManager custom class, and the FourPanelMedicalViewerApp app are also attached to this example as supporting files. For information on running the app, see the Explore 3-D and 4-D Medical Volumes Using App section. For information on using the custom UI components in standalone mode, see the Use Custom UI Components in Standalone Mode section.
You can also open this example from the App Designer home page by clicking Show examples in the Apps section of the home page and selecting Visualize Medical Volume from the list of examples.
You can customize the code of the app in the attached supporting files. For information on customizing the app, see the Customize the App section.
App Layout Design
The FourPanelMedicalViewerApp app has two main regions: a toolstrip and a working area.
The toolstrip contains these sections:
Import — Consists of UI components used to import medical volume data from a file, the workspace, or a PACS server.
Crosshair — Consists of UI components used to control crosshair navigation.
Rendering Style — Consists of UI components used to specify the rendering style.
Time-Series Browser — Consists of UI components related to playback controls that become available only when you load a 4‑D time‑series volume.
When the user selects the option to import data from a PACS server, the app opens the PACSConnectionApp in embedded mode to enable the user to establish a connection with a PACS server and retrieve data. For more information on building the PACSConnectionApp app, see Create an App for Retrieving DICOM Data from PACS Server.
The working area of the app consists of a single section containing an instance of the custom UI component FourPanelMedicalViewer, used to visualize the medical volume.
The FourPanelMedicalViewer component has four visualization panels, consisting of a panel for each of the orthogonal slices and another panel for the 3-D visualization. The three orthogonal slice panels each have an ImageStackScrubber component to display and scroll through image slices. The fourth panel, for the 3-D volume visualization, displays the volume using the volshow function. The handle of the displayed image is a Volume object. A Viewer object is the parent of the Volume object. For more information about the Volume object, see Volume Properties. For more information about the Viewer object, see Viewer Properties.

Create the ImageStackScrubber Custom UI Component
The ImageStackScrubber component provides a single‑plane 2‑D slice viewer with a vertical slider for navigating through the slices of a medical volume. It encapsulates all logic related to displaying a 2‑D slice from a medical volume, scrolling through slices along a selected anatomical plane, and handling crosshair interaction and emitting events when the slice position or crosshair location changes.
The ImageStackScrubber custom component includes these properties:
Volume—medicalVolumeobject containing 3‑D or 4‑D data.SlicePlane— Anatomical plane of slices ("transverse","coronal", or"sagittal").SliceIndex— Current slice index within the selected plane.FrameIndex— Current time frame for 4‑D volumes.Crosshair— Enables or locks crosshair interaction.CrosshairPosition— Current crosshair position, in world coordinates.
Custom UI components inherit from the matlab.ui.componentcontainer.ComponentContainer class and have two primary methods: setup and update. The setup method and other custom functions create the underlying UI elements, including the 2‑D viewer and slice slider. The update method and other custom functions refresh the displayed image whenever the volume, slice index, slice plane, or frame index changes. When the user assigns a new volume, the component resets its view, configures spatial calibration based on volume geometry, and updates the slider limits to match the selected slicing plane.
The component has these events:
ValueChanged— Occurs when the slice index changes through slider interaction.CrosshairMoving— Occurs continuously as the user drags the crosshair.CrosshairMoved— Occurs after the user completes crosshair movement.
These events enable a parent component to synchronize slice positions across multiple viewers.
Create the FourPanelMedicalViewer Custom UI Component
The FourPanelMedicalViewer component arranges and synchronizes three ImageStackScrubber components and a 3‑D volume rendering. This component provides a unified visualization for medical volumes by displaying orthogonal transverse, sagittal, and coronal slices, rendering the full 3‑D volume using volshow, synchronizing slice indices and crosshair positions across all views, and supporting time‑series updates for 4‑D volumes.
The component creates a four‑panel grid.
Transverse panel — Contains an
ImageStackScrubberconfigured for transverse slicing.Sagittal panel — Contains an
ImageStackScrubberconfigured for sagittal slicing.Coronal panel — Contains an
ImageStackScrubberconfigured for coronal slicing.3D Volume panel — Contains a 3‑D viewer and a
volshowobject.
The FourPanelMedicalViewer custom component includes these properties:
Volume—medicalVolumeobject displayed in all views.TimeFrameIndex— Current time frame for 4‑D volumes.RenderingStyle— 3‑D rendering style applied to the volume.Crosshair— Enables or locks crosshair navigation across all slice viewers.
When the user imports data into the parent FourPanelMedicalViewerApp app, the component sets the Volume property and calls the initializeViewers method. This method validates that the input volume is either 3‑D or 4‑D, checks spatial geometry and ensures consistent orientation, routes the volume into each ImageStackScrubber instance, and resets the time frame index to the first frame.
function initializeViewers(comp) % INITIALIZEVIEWERS Configure viewers for newly loaded volume numDimensions = ndims(comp.Volume_I.Voxels); % Check if volume is 4D time-series if numDimensions == 4 comp.IsTimeSeries = true; elseif numDimensions == 3 comp.IsTimeSeries = false; else error("Volume must be 3D or 4D"); end % Verify volume has affine geometry if ~medical.internal.spatial.isAffineEnough(comp.Volume_I.VolumeGeometry) error("Volume must be affine"); end % Update all slice viewers comp.TransverseViewer.Volume = comp.Volume_I; comp.SagittalViewer.Volume = comp.Volume_I; comp.CoronalViewer.Volume = comp.Volume_I; if ~isVolumeAxesNotAligned(comp.TransverseViewer) comp.Volume_I.VolumeGeometry = orient(comp.Volume_I.VolumeGeometry,"LPS+"); end % Reset to first time frame comp.TimeFrameIndex = 1; end
Each ImageStackScrubber has crosshair events when the user interacts with a slice. The FourPanelMedicalViewer component listens for these events and converts the crosshair position from world coordinates to intrinsic volume indices, updates the slice indices in all other slice viewers, and updates the crosshair positions across all slice viewers. Each ImageStackScrubber also has an event when the user scrolls through image slices. The FourPanelMedicalViewer component listens for this event and updates the slice views and crosshair positions accordingly. The crosshairMoving, sliceChanged, and updateCrosshairPosition methods define these behaviors.
function crosshairMoving(comp,event) %CROSSHAIRMOVING Handle active crosshair movement % Called continuously while user is dragging the crosshair if comp.IsUpdatingCrosshair || isempty(comp.Volume_I) return; end comp.IsUpdatingCrosshair = true; comp.TransverseViewer.CrosshairPosition = event.Position; comp.SagittalViewer.CrosshairPosition = event.Position; comp.CoronalViewer.CrosshairPosition = event.Position; [sagittalIndex,coronalIndex,transverseIndex] = worldToIntrinsic(comp.Volume.VolumeGeometry,event.Position(1),event.Position(2),event.Position(3)); comp.TransverseViewer.SliceIndex = round(transverseIndex); comp.SagittalViewer.SliceIndex = round(sagittalIndex); comp.CoronalViewer.SliceIndex = round(coronalIndex); comp.IsUpdatingCrosshair = false; end
function sliceChanged(comp,event) %SLICECHANGED Handle slice index change % Updates crosshair position when user scrolls through slices updateCrosshairPosition(comp); end
function updateCrosshairPosition(comp) %UPDATECROSSHAIRPOSITION Synchronize crosshair position based on slice indices % Converts current slice indices to world coordinates and updates % crosshair position in all viewers % Get current slice indices [sagittalSliceIdx,coronalSliceIdx,transverseSliceIdx] = getSliceIndices(comp); % Convert to world coordinates [crosshairPosition(1),crosshairPosition(2),crosshairPosition(3)] = intrinsicToWorld(comp.Volume.VolumeGeometry,sagittalSliceIdx,coronalSliceIdx,transverseSliceIdx); % Update crosshair in all viewers comp.TransverseViewer.CrosshairPosition = crosshairPosition; comp.CoronalViewer.CrosshairPosition = crosshairPosition; comp.SagittalViewer.CrosshairPosition = crosshairPosition; end
When the volume or time frame itself changes, the component updates the volshow object by assigning the appropriate 3‑D data for the current time frame and updating the spatial transformation and orientation axes labels.
Define App Methods
The app uses methods to load volumes into the app, enable time-series controls and interactions, and control the app state. The app also uses some helper functions to improve code readability and code reusability. These are some of the important app methods.
Methods for Startup
When the app starts, the startupFcn method creates an instance of the FourPanelMedicalViewer component and places it in the main display area of the app. The app itself does not render medical data. Instead, it delegates all visualization to the FourPanelMedicalViewer component and coordinates the user input. The startupFcn method also initializes the crosshair state of the viewer based on the current value of the Crosshair button in the app toolstrip, ensuring that app‑level controls and component state are aligned from the beginning.
function startupFcn(app) app.MedicalViewerComponent = FourPanelMedicalViewer(app.MainGridLayout); if app.CrosshairButton.Value app.MedicalViewerComponent.Crosshair = "on"; else app.MedicalViewerComponent.Crosshair = "off"; end end
Methods to Load Data from Different Sources
The loadVolumeFromFile, loadVolumeFromFolder, and loadVolumeFromPACS methods handle user interactions for specific import sources.
loadVolumeFromFileloads medical volume from a single medical image file, such as a DICOM or NIfTI file.loadVolumeFromFolderloads the medical volume from a folder containing a DICOM series.loadVolumeFromPACSimports a medical volume from a PACS server queried through a separate dialog.
In each of these methods, the app constructs a medicalVolume object and assigns it to the Volume property of the FourPanelMedicalViewer component. This assignment is the trigger that initializes all slice viewers and the 3‑D rendering.
function loadVolumeFromFile(app,event) % LOADVOLUMEFROMFILE Load medical volume from a single file [fileName,filePath] = uigetfile( ... ["*.nii;*.dcm;*.mhd;*.nrrd'","Medical Image Files (*.nii, *.dcm, *.mhd, *.nrrd)"], ... "Select Medical Volume File"); if isequal(fileName,0) return; % User cancelled end fullFilePath = fullfile(filePath,fileName); try volumeData = medicalVolume(fullFilePath); app.MedicalViewerComponent.Volume = volumeData; % Update time-series controls based on loaded volume updateTimeSeriesControls(app); catch ME uialert(app.UIFigure,ME.message,"File Load Error"); end end
function loadVolumeFromFolder(app,event) % LOADVOLUMEFROMFOLDER Load medical volume from DICOM folder folderPath = uigetdir('',"Select Folder Containing DICOM Files"); if isequal(folderPath,0) return; % User cancelled end try volumeData = medicalVolume(folderPath); app.MedicalViewerComponent.Volume = volumeData; % Update time-series controls based on loaded volume updateTimeSeriesControls(app); catch ME uialert(app.UIFigure,ME.message,"Folder Load Error"); end end
function loadVolumeFromPACS(app,event) % LOADVOLUMEFROMPACS Open PACS dialog for importing medical volumes if isempty(app.PACSDialog) || ~isvalid(app.PACSDialog) % Create new PACS dialog configured for app integration app.PACSDialog = PACSConnectionApp(true); % Listen for successful import events addlistener(app.PACSDialog,"ImportIsSuccessful", ... @(src,evt)onPACSImportCompleted(app,src)); end % Show the PACS dialog app.PACSDialog.Visible = "on"; end
When the user selects the option to import data from a PACS server, the app opens a separate instance of the PACSConnectionApp that provides a dialog for the user to establish a connection with a PACS server, query the server, and retrieve data from the server. The onPACSImportCompleted method listens for the completion event of the PACSConnectionApp. When the event occurs, the app retrieves the downloaded data path, creates a medicalVolume, and assigns it to the viewer component.
function onPACSImportCompleted(app,pacsDialog) % ONPACSIMPORTCOMPLETED Handle successful PACS data import % Get the downloaded filepath from PACS dialog downloadedPath = pacsDialog.Filepath; if isempty(downloadedPath) uialert(app.UIFigure, ... "No data was downloaded from PACS server", ... "Import Failed"); return; end % Hide PACS dialog pacsDialog.Visible = "off"; try % Load the medical volume and set it to the viewer component volumeData = medicalVolume(downloadedPath); app.MedicalViewerComponent.Volume = volumeData; % Update time-series controls based on loaded volume updateTimeSeriesControls(app); catch ME % Show error message uialert(app.UIFigure, ... "Failed to load volume from PACS data:" + newline + string(ME.message), ... "Import Error", ... Icon="error"); end end
Methods to Manage Time-Series Controls
Methods that manage time-series controls, manage how the app switches between static 3‑D exploration and 4‑D time‑series browsing. After loading a volume, the app queries the FourPanelMedicalViewer component to determine whether the data contains a time dimension. Based on this check, the app enables or locks the time‑series browser controls. The updateTimeSeriesControls and enableTimeSeriesControls methods define these behaviors.
function updateTimeSeriesControls(app) % UPDATETIMESERIESCONTROLS Update time-series controls based on volume % Stop animation if playing if app.IsPlaying stopAnimation(app); end if isTimeSeriesVolume(app.MedicalViewerComponent) enableTimeSeriesControls(app,true); else enableTimeSeriesControls(app,false); end end
function enableTimeSeriesControls(app,enableFlag) % ENABLETIMESERIESCONTROLS Enable or lock time-series playback controls if enableFlag numTimeFrames = getNumberOfTimeFrames(app.MedicalViewerComponent); controlState = "on"; app.TimeFrameSlider.Limits = [1 numTimeFrames]; app.TimeFrameSlider.Value = 1; app.FrameCounterLabel.Text = "1/" + num2str(numTimeFrames); else controlState = "off"; app.TimeFrameSlider.Value = 1; app.FrameCounterLabel.Text = ''; end app.PreviousFrameButton.Enable = controlState; app.PlayButton.Enable = controlState; app.NextFrameButton.Enable = controlState; app.TimeFrameSlider.Enable = controlState; app.TimeSeriesBrowserLabel.Enable = controlState; end
The onPreviousFrameButtonPushed, onNextFrameButtonPushed, and onTimeFrameSliderChanged methods work together to control temporal navigation. Each method updates the shared property TimeFrameIndex on the FourPanelMedicalViewer component. The app never updates individual slice viewers or the 3‑D renderer directly. Changing the time‑frame index is sufficient to refresh all views.
function onPreviousFrameButtonPushed(app,event) % PREVIOUSFRAMEBUTTONPUSHED Navigate to previous time frame currentFrame = app.MedicalViewerComponent.TimeFrameIndex - 1; numTimeFrames = getNumberOfTimeFrames(app.MedicalViewerComponent); % Wrap around to last frame if at beginning if currentFrame < 1 currentFrame = numTimeFrames; end app.MedicalViewerComponent.TimeFrameIndex = currentFrame; app.TimeFrameSlider.Value = currentFrame; app.FrameCounterLabel.Text = num2str(currentFrame) + "/" + num2str(numTimeFrames); end
function onNextFrameButtonPushed(app,event) % ONNEXTFRAMEBUTTONPUSHED Navigate to next time frame currentFrame = app.MedicalViewerComponent.TimeFrameIndex + 1; numTimeFrames = getNumberOfTimeFrames(app.MedicalViewerComponent); % Wrap around to first frame if at end if currentFrame > numTimeFrames currentFrame = 1; end app.MedicalViewerComponent.TimeFrameIndex = currentFrame; app.TimeFrameSlider.Value = currentFrame; app.FrameCounterLabel.Text = num2str(currentFrame) + "/" + num2str(numTimeFrames); end
function onTimeFrameSliderChanged(app,event) % ONTIMEFRAMESLIDERCHANGED Handle slider value changes numTimeFrames = getNumberOfTimeFrames(app.MedicalViewerComponent); roundedValue = round(event.Value); app.MedicalViewerComponent.TimeFrameIndex = roundedValue; app.TimeFrameSlider.Value = roundedValue; app.FrameCounterLabel.Text = num2str(roundedValue) + "/" + num2str(numTimeFrames); end
Methods to Animate 4-D Data
When animation playback begins, the app starts a timer that advances the time‑frame index at a fixed rate. While playback is active, the app locks manual navigation controls to prevent conflicting updates. Stopping the animation restores manual control and ensures that the app and viewer component return to a consistent state. The startAnimation, stopAnimation, and advanceFrame methods define these behaviors.
function startAnimation(app) % STARTANIMATION Start playing through time frames app.IsPlaying = true; % Disable other navigation controls during playback app.PreviousFrameButton.Enable = "off"; app.NextFrameButton.Enable = "off"; app.TimeFrameSlider.Enable = "off"; % Create and start timer for animation if isempty(app.AnimationTimer) || ~isvalid(app.AnimationTimer) app.AnimationTimer = timer( ... ExecutionMode="fixedRate", ... Period=0.1, ... TimerFcn=@(~,~)advanceFrame(app)); end start(app.AnimationTimer); end
function stopAnimation(app) % STOPANIMATION Stop playing through time frames app.IsPlaying = false; app.PlayButton.Value = false; % Re-enable navigation controls app.PreviousFrameButton.Enable = "on"; app.NextFrameButton.Enable = "on"; app.TimeFrameSlider.Enable = "on"; % Stop and delete timer if ~isempty(app.AnimationTimer) && isvalid(app.AnimationTimer) stop(app.AnimationTimer); end end
function advanceFrame(app) % ADVANCEFRAME Move to next frame during animation playback onNextFrameButtonPushed(app); end
Explore 3-D and 4-D Medical Volumes Using App
Open the ImageStackScrubber custom UI component in App Designer. In the Designer tab of the App Designer toolstrip, select the Configure for Apps option. In the dialog that opens, select OK. When the App designer displays a success message stating that the metadata has been updated, select the Add to Path option. Repeat this process for the FourPanelMedicalViewer custom UI component.
Run the FourPanelMedicalViewerApp app.
Load a medical volume into the app. To load a volume from a file, on the app toolstrip, select Import and then From File. In the dialog that opens, select a supported file. To load a volume from a folder, select Import and then From Folder. In the dialog that opens, browse to a folder containing a DICOM series and select the folder. To load a volume from a PACS server, select Import and then From PACS Server. In the PACSConnectionApp that opens, configure and establish a connection the PACS server, query the PACS server, and retrieve data from the PACS server. For more information on how to use the PACSConnectionApp app, see the Retrieve DICOM Data from PACS Server Using App section of the Create an App for Retrieving DICOM Data from PACS Serverexample.

To interact with the image slices and crosshair, toggle the Crosshair state button at the top of the app to turn crosshair navigation on or off. When you enable crosshair navigation, you can drag the crosshair in any of the 2-D panels. You can use a mouse scroll wheel or the slider in any 2-D orthogonal visualization panel to move through slices in that plane. The app updates the crosshair position to reflect the new slice index.

You can also change the 3-D rendering style using the Rendering Style drop-down in the app toolstrip.
Select
VolumeRenderingto see a standard opacity-based rendering.Select
MaximumIntensityProjectionto highlight high-intensity structures.Select
GradientOpacityto emphasize boundaries and edges.

When you load a 4-D volume, such as a dynamic contrast-enhanced scan, a cardiac cine MRI, or a functional MRI, the app detects that the volume is time-varying and enables the time-series controls. Use the Previous and Next options to step through time frames. Drag the time-frame slider to jump to a specific frame. Select Play to animate the volume over time. All 2‑D slice views and the 3‑D rendering update synchronously for each frame to provide a synchronized 4-D exploration experience.

Use Custom UI Components in Standalone Mode
You can reuse the FourPanelMedicalViewer and ImageStackScrubber custom UI components outside of the app in your custom apps or scripts.
Standalone Four-Panel Medical Viewer
Load medical volume data into the workspace as a medicalVolume object.
zipFile = matlab.internal.examples.downloadSupportFile("medical","MedicalVolumeDICOMData.zip"); filepath = fileparts(zipFile); unzip(zipFile,filepath) dataFolder = fullfile(filepath,"MedicalVolumeDICOMData","LungCT01"); mvol = medicalVolume(dataFolder);
Create a figure for the FourPanelMedicalViewer component.
f = uifigure; g = uigridlayout(f,[1 1]);
Create the FourPanelMedicalViewer component in the parent figure.
viewer = FourPanelMedicalViewer(g);
To visualize the medical volume, specify the medicalVolume object as the Volume property of the FourPanelMedicalViewer component.
viewer.Volume = mvol;
Enable crosshair navigation, and specify a 3-D rendering style.
viewer.Crosshair = "on"; viewer.RenderingStyle = "GradientOpacity";

Standalone Image Stack Scrubber
Load medical volume data into the workspace as a medicalVolume object.
zipFile = matlab.internal.examples.downloadSupportFile("medical","MedicalVolumeDICOMData.zip"); filepath = fileparts(zipFile); unzip(zipFile,filepath) dataFolder = fullfile(filepath,"MedicalVolumeDICOMData","LungCT01"); mvol = medicalVolume(dataFolder);
Create a figure for the ImageStackScrubber component.
f = uifigure; g = uigridlayout(f,[1 1]);
Create the ImageStackScrubber component in the parent figure. To visualize the medical volume, specify the medicalVolume object as the Volume property of the ImageStackScrubber component.
scrubber = ImageStackScrubber(g,Volume=mvol);
Specify the 2-D orthogonal plane and slice index for visualization.
scrubber.SlicePlane = "transverse";
scrubber.SliceIndex = 45;
Customize the App
You can customize the code of the FourPanelMedicalViewer and ImageStackScrubber custom UI components and the FourPanelMedicalViewerApp app in the attached supporting files.
For example, you can add sliders or numeric edit fields to the app to control intensity windowing and apply them to all 2-D and 3-D views. To enable this intensity windowing, create a dependent DisplayRange property in the ImageStackScrubber component and implement corresponding set and get methods. Then, when the display range is adjusted from the app, update the DisplayRange property in ImageStackScrubber using these set and get methods.
function set.DisplayRange(comp,range) % Set display range comp.Image.DisplayRange = range; end function range = get.DisplayRange(comp) % Get information of display range range = comp.Image.DisplayRange; end
You can also add ROI tools, such as for freehand, polygon, angle, or point drawing, in the viewer of an ImageStackScrubber to draw regions of interest on slices, which you can use to compute areas, intensity statistics, or other measurements, and to store and export ROI information to the workspace.
To customize the app, you can choose one of these options:
Open the attached MLAPP files in App Designer and edit the code in the Code View.
Open the attached MLAPP files in App Designer, select Share in the Designer tab and then Export to MATLAB Class (.m), and save the M file. You can then edit the M file.