user3067629
user3067629

Reputation: 23

how to create a 3d sparse like matrix in octave

my Problem is difficult or too simple. So I've been using sparse to creat a matrix from different vectors (example here)

I use sparse(i,j,s,m,n) where i and j are allocations for particles i derived with floor etc. (it is particle in cell simulation).

this is for 1D. I want to vectorize this problem for 2D and got the problem that i can't creat 3D sparse matrices in octave.

I'm really no pro with octave and i'm searching for a solution that i can put the values from s nicely into a matrix according to the i and j values.

for example: i got particle one in cell x=2 and y=2 than i want to have a matrix with value from particle one in (1,2,2,value). is there a way without much if's and for's?

Upvotes: 2

Views: 1051

Answers (2)

gaborous
gaborous

Reputation: 16570

Sparse NDArray is not possible in either Octave nor Matlab. However, there is a class for Matlab which implements Sparse NDArray, although the performance will probably be not optimal, it will still probably be a lot better than using a cell array since it internally represents the sparse NDArray as a simple 2D sparse matrix:

http://www.mathworks.com/matlabcentral/fileexchange/29832-n-dimensional-sparse-arrays

Since v4, Octave now supports classdef. I did not try it yet, but even if it does not work yet, it will probably soon. And anyway, you can see how it was done in the script and make a non-class, all functional version by applying the same idea (using a 2D sparse matrix that you manipulate with custom functions to do whatever operations you want in a ND space).

Upvotes: 0

carandraug
carandraug

Reputation: 13081

At the moment is not possible to have N-dimensional sparse matrices in Octave. You can see this with the following example which tries to reshape a 3x9 sparse matrix into 3x3x3:

octave> sp = sparse (2, 6, 1, 3, 9)
sp =

Compressed Column Sparse (rows = 3, cols = 9, nnz = 1 [3.7%])

  (2, 6) ->  1

octave> reshape (sp, [3 3 3])
warning: reshape: sparse reshape to N-d array smashes dims
ans =

Compressed Column Sparse (rows = 3, cols = 9, nnz = 1 [3.7%])

  (2, 6) ->  1

What you can do is to have a cell array of sparse matrices. So for a particle at KxMxN you could have data{k} = sparse (M, N, value) and access it with data{k}(m,n). It's not ideal but depending on how you get your data organized you may make things more or less readable.

Upvotes: 1

Related Questions