the dimension of matrix when using 'sparse' to generate sparse matrix

142 Ansichten (letzte 30 Tage)
li
li am 6 Dez. 2025 um 16:01
Beantwortet: Matt J vor etwa 17 Stunden
Why matlab has removed the high dimension operation of sparse?
I used to generate 3D sparse matrix using sparse. However, I find an error message when using this function says: Error using sparse, inputs must be 2-D.
Is this problem solvable?
  19 Kommentare
Umar
Umar am 10 Dez. 2025 um 5:07
Verschoben: Matt J vor etwa 5 Stunden

@Li, Your screenshots actually pin down the root of the problem. MATLAB isn’t calling the built-in “tril” at all — it’s dispatching to the one inside “ndSparse/tril.m”. Once that happens, the behavior becomes completely different from what your code used to rely on.

Inside that file, there’s a hard-coded dimension check that rejects anything that isn’t strictly 2-D. The moment your 3-D array comes in from spblkdiag, that check fires and you get the “supports only 2D” error. That alone is enough to break the version of your code that worked last year.

Then there’s the second issue you caught in your screenshot. That same tril.m tries to do

zeros(size(A),'like',A)

but ndSparse objects don’t implement “like”, so MATLAB complains exactly as shown: “Argument following “like” must be a variable…”. That’s a toolbox bug, not something you caused.

Put together, once MATLAB starts using the ndSparse version of tril, it can’t handle your 3-D input and it can’t handle its own “like” syntax. That explains why your old code ran fine before — back then, MATLAB was calling the built-in tril instead of the ndSparse one.

If you want everything to behave the way it used to, the clean fix is to patch @ndSparse/tril.m, so it drops the “like” call and processes N-D data slice by slice. After that, your original code will work again without any changes.

The workaround I gave — looping over the third dimension before calling spblkdiag — is completely valid and usually fast enough. But if restoring the original one-line style is important to you, then updating tril.m by you is the way to get there.

li
li vor etwa 7 Stunden
Verschoben: Matt J vor etwa 5 Stunden
Hi, @Umar,
I have attached the files.m. Please check. I use the testsp.m to test the effectiveness of the codes.
Thank you very much for your kindly help!

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Umar
Umar am 7 Dez. 2025 um 1:18
Bearbeitet: Umar am 7 Dez. 2025 um 1:20
Diese(r) Antwort wurde durch Dyuman Joshi markiert

Hi @li,

I saw your question about MATLAB removing 3D sparse matrix support, and I wanted to help clarify what's happening. Both @Torsten and @Walter Roberson are absolutely correct in their responses to you. MATLAB's native sparse function has actually never supported 3D or N-dimensional arrays. It's always been limited to 2D matrices only, going all the way back to before R2006a.

I know this might be confusing because when you call something like sparse(3, 3, 3), MATLAB doesn't throw an error right away. Instead, it interprets this as the sparse(i, j, v) syntax, where i=3 is the row index, j=3 is the column index, and v=3 is the value. So you end up with a 2D matrix that has a single element at position (3,3) with value 3, not a 3D array at all. This might be why you thought it was working before.

The error message you're seeing now, " Error using sparse, inputs must be 2-D", is actually the function working correctly and enforcing its documented 2D-only limitation. Walter mentioned that the only recent change to sparse was in R2025a, when they added support for single precision matrices alongside the existing double and logical types. That's the first major enhancement in many years, and it had nothing to do with removing any dimensional capabilities.

As Torsten suggested, if you truly need 3D sparse functionality, you'll want to look at the N-dimensional sparse arrays contribution on the MATLAB File Exchange ( https://uk.mathworks.com/matlabcentral/fileexchange/29832-n-dimensional-sparse-arrays ). That's a third-party solution that provides the ndSparse class, which can handle the multidimensional sparse arrays that native MATLAB cannot.

I tested this myself to confirm, and here's some code that demonstrates the 2D limitation:

S1 = sparse(5, 5);
disp('2D sparse matrix created successfully');
disp(S1);
% This also works - 2D sparse with values
i = [1 2 3];
j = [1 2 3];
v = [10 20 30];
S2 = sparse(i, j, v, 5, 5);
disp('2D sparse matrix with values:');
disp(S2);
% This doesn't create 3D - it creates 2D with element at (3,3)
S3 = sparse(3, 3, 3);
disp('This is still 2D:');
disp(['Dimensions: ' num2str(size(S3))]);
disp(['Number of dimensions: ' num2str(ndims(S3))]);
% To truly get the error, try converting a 3D array
try
  A_3D = rand(3, 3, 3);
  S_3D = sparse(A_3D);
catch ME
  disp('Error when trying true 3D:');
  disp(ME.message);
end

Note: please see attached.

Hope this helps clar things up. The functionality you're looking for was never in base MATLAB, so nothing was actually removed. You'll need to use a File Exchange solution for 3D sparse arrays.

  4 Kommentare
Umar
Umar am 7 Dez. 2025 um 17:33

Hi @Catalytic,

I want to clarify the intent of my answer. My goal was to provide additional value beyond what was already stated by others:

I explicitly demonstrated the difference between sparse(3,3,3) and a true 3D array with a reproducible MATLAB script. This helps users see why MATLAB behaves the way it does.

I included a practical solution using cell arrays of sparse matrices for 3D data, which is not mentioned in the previous comments. I provided links to official documentation and historical MathWorks support, showing that 3D sparse matrices were never supported, which gives authoritative context.

The combination of explanation, demonstration, and practical workaround is meant to be a complete, step-by-step answer to help users understand the limitation and a working alternative.

I hope this clarifies why this answer adds unique value, rather than simply repeating earlier comments.Let me know what is your feedback to @Li comments, could you please contribute your thoughts, we will really appreciate it.

Umar
Umar am 7 Dez. 2025 um 20:19

Note: This answer has been revised in my updated response below, which incorporates technical clarifications from @Walter Roberson.

Melden Sie sich an, um zu kommentieren.


Umar
Umar am 7 Dez. 2025 um 17:47
Bearbeitet: Umar am 7 Dez. 2025 um 20:26

Hi @Li,

After going through recent comments, I wanted to provide a clear explanation of the situation regarding 3D sparse matrices in MATLAB, step by step.

You asked, “Why MATLAB does not support high-dimensional sparse matrices”

Feedback: MATLAB’s `sparse` function has never supported 3D or N-dimensional sparse arrays. Sparse matrices in MATLAB are always 2D (rows × columns). According to MathWorks Support (2009), “MATLAB only supports two-dimensional sparse matrices” [link]( < Mathworks > )

Also, the official `sparse` documentation also only describes 2D usage and makes no mention of N-dimensional variants ([link]( Mathworks )).

Therefore, there was never a “high-dimension operation” to remove; the function was never designed for that.

Edit comments: As @Walter Roberson demonstrated recently, this limitation is fundamental and not related to syntax conflicts:

sparse(ones(2,3,4))
Error using sparse
Inputs must be 2-D.

This definitively shows MATLAB rejects true 3D arrays regardless of the syntax used.

You asked, “Why you see the error “Inputs must be 2-D”

Feedback: When you pass a true 3D array to `sparse`, MATLAB rejects it, because the sparse format is strictly 2D. Even if you try to `reshape` a 1D or 2D sparse matrix into 3D, MATLAB internally flattens the extra dimensions, returning a 2D matrix rather than a true 3D sparse array.

You asked, “Practical solutions to mimic 3D sparse arrays”

Feedback: Since MATLAB cannot natively create 3D sparse matrices, there are two practical approaches:

1. Cell array of 2D sparse slices

You can create a 3D-like structure by storing each 2D slice as a separate sparse matrix inside a cell array. Example discussion here: [link]( Mathworks )

2. Use third-party N-D sparse implementations

The MATLAB File Exchange has a solution called `ndSparse` for true N-dimensional sparse arrays: [link]( < ndSparse > ) as already suggested by @Torsten in his comments section.

Demonstration Script

%% Step 1: Error for a true 3D array
try
  A_3D = rand(3,3,3);
  S_3D = sparse(A_3D);
catch ME
  disp('Error for true 3D array:');
  disp(ME.message);
end
%% Step 2: sparse(3,3,3) creates 2D matrix
S = sparse(3,3,3);
disp('Size of sparse(3,3,3):');
disp(size(S));
disp('Number of dimensions:');
disp(ndims(S));
%% Step 3: Mimic 3D sparse matrix with cell array
nSlices = 3;  
slices = cell(1,nSlices);
for k = 1:nSlices
  slices{k} = sparse(rand(3,3));  % 2D sparse slice
end
disp('Slice 3:');
disp(slices{3});
% Access an element
val = slices{2}(2,3);
disp(['Element (2,3) in slice 2: ', num2str(val)]);

Results: please see attached

Explanation: * True 3D array —> error: “Inputs must be 2‑D” * sparse(3,3,3) —> creates a 2D sparse matrix * Cell array —> successfully mimics a 3D sparse structure

This explanation is chronological and addresses both of your questions:

1. MATLAB never supported high-dimensional sparse matrices (so nothing was removed). 2. You can practically work around the 2D limitation using cell arrays or the “ndSparse” class.

Hope this clarifies everything and provides a concrete solution. If you need further assistance, please let us know.

  2 Kommentare
Walter Roberson
Walter Roberson am 7 Dez. 2025 um 18:49
Although sparse(rows, columns, pages) does not work, hypothetically the prime syntax sparse(A) could work for 3D A. But it does not work.
sparse(ones(2,3,4))
Error using sparse
Inputs must be 2-D.
This does not rely upon syntax conflicts, which themselves do not prove the point.
Umar
Umar am 7 Dez. 2025 um 20:15

Thank you @Walter Roberson for that crucial clarification. You're absolutely right— the sparse(ones(2,3,4)) example definitively demonstrates the 2D limitation without any syntax ambiguity. This is a much cleaner and more rigorous proof than my sparse(3,3,3) explanation.

I genuinely appreciate you taking the time to provide this correction, and I always respect and value your expertise in helping the MATLAB community understand these technical details correctly.

Melden Sie sich an, um zu kommentieren.


Matt J
Matt J vor etwa 5 Stunden
With a slight reimplementation of tril3d, the test code seems to work:
% test spblkdiag tril ndSparse
z1=rand(8,8,20);
z2=tril3d(spblkdiag(z1(:,:,1:19)+z1(:,:,2:20)));
whos z1 z2
Name Size Bytes Class Attributes z1 8x8x20 10240 double z2 8x8x19 19640 ndSparse sparse
% test tril3D blkdiag3d
z1=rand(8,8,20);
z2=tril3d(blkdiag3d(z1(:,:,1:19)+z1(:,:,2:20)));
whos z1 z2
Name Size Bytes Class Attributes z1 8x8x20 10240 double z2 152x152 184832 double
function result = tril3d(A, k)
% apply tril to each page of a 3D array
% usage: result = tril3d(A) or result = tril3d(A, k) for diagonal
%offset
if nargin < 2
k = 0; % main diagonal by default
end
[m,n,p]=size(A);
if p==1
result=tril(A,k);
else
result=A.*tril(true(m,n),k);
end
end

Kategorien

Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by