Ask Your Question
4

How can a sparse array be implemented in Fortran?

asked 2023-07-03 02:09:16 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-03 02:15:01 +0000

huitzilopochtli gravatar image

A sparse array in Fortran can be implemented using a combination of arrays and linked lists. Each element in the sparse array can be represented by a node in a linked list, and the array itself can be an array of pointers to these nodes.

Here is an example implementation:

type sparse_node
   integer :: value
   integer :: row, col
   type(sparse_node), pointer :: next_row, next_col
end type

type(sparse_node), pointer :: row_start(:), col_start(:)

integer :: max_rows, max_cols

! Initialize the linked lists
allocate(row_start(max_rows), col_start(max_cols))
do i = 1, max_rows
   row_start(i) => null()
enddo
do j = 1, max_cols
   col_start(j) => null()
enddo

! Insert a value into the sparse array at position (i, j)
subroutine insert_sparse(i, j, value)
   type(sparse_node), pointer :: node
   allocate(node)
   node%value = value
   node%row = i
   node%col = j
   node%next_row => row_start(i)
   row_start(i) => node
   node%next_col => col_start(j)
   col_start(j) => node
end subroutine

! Get a value from the sparse array at position (i, j)
function get_sparse(i, j) result(value)
   integer :: i, j
   type(sparse_node), pointer :: node
   value = 0
   node => row_start(i)
   do while (associated(node))
      if (node%col == j) then
         value = node%value
         exit
      endif
      node => node%next_row
   enddo
end function

In this implementation, max_rows and max_cols are the maximum dimensions of the array, and insert_sparse inserts a value into the sparse array at position (i, j). get_sparse retrieves a value from the array at position (i, j). The row_start and col_start arrays hold pointers to the first node in each row and column, respectively.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-03 02:09:16 +0000

Seen: 8 times

Last updated: Jul 03 '23