setDiagonalMatrix

C++ Function Reference

1 Signature

void BigDataStatMeth::setDiagonalMatrix(BigDataStatMeth::hdf5Dataset *dsMat, Rcpp::NumericVector intNewDiagonal)

2 Description

Sets the diagonal elements of a matrix stored in HDF5 format.

3 Parameters

  • dsMat (BigDataStatMeth::hdf5Dataset *): Target HDF5 dataset containing the matrix
  • intNewDiagonal (Rcpp::NumericVector): Vector of new diagonal values to set

4 Details

dsMatTarget HDF5 dataset containing the matrix intNewDiagonalVector of new diagonal values to set Implementation approach:Writes diagonal elements one at a timeUses HDF5 block writing for efficient accessPreserves existing non-diagonal elements

5 Call Graph

Function dependencies

6 Source Code

File: inst/include/hdf5Algebra/matrixDiagonal.hppLines 104-136

inline void setDiagonalMatrix(BigDataStatMeth::hdf5Dataset* dsMat, Rcpp::NumericVector intNewDiagonal)
    {
        try {
            const hsize_t DIAG_BLOCK_SIZE = 256;
            hsize_t matrix_size = intNewDiagonal.size();
            std::vector<hsize_t> stride = {1, 1}, block = {1, 1};
            
            for (hsize_t block_start = 0; block_start < matrix_size; block_start += DIAG_BLOCK_SIZE) {
                hsize_t N = std::min(DIAG_BLOCK_SIZE, matrix_size - block_start);
                
                std::vector<hsize_t> offset = {block_start, block_start};
                std::vector<hsize_t> count  = {N, N};
                
                // Read block as raw HDF5 row-major bytes.
                // block_data[i*N + j] == HDF5[block_start+i, block_start+j]
                std::vector<double> block_data(N * N);
                dsMat->readDatasetBlock(offset, count, stride, block, block_data.data());
                
                // Diagonal elements sit at block_data[k*N + k] (same index in
                // HDF5 row-major and R column-major for the diagonal).
                // Write new diagonal values directly — no transposition needed.
                for (hsize_t k = 0; k < N; ++k)
                    block_data[k * N + k] = intNewDiagonal[block_start + k];
                
                // Write back using the vector overload, which passes the raw
                // row-major bytes straight to HDF5 without any R/Rcpp wrapping.
                dsMat->writeDatasetBlock(block_data, offset, count, stride, block);
            }
            
        } catch(std::exception& ex) {
            Rcpp::stop("c++ exception setDiagonalMatrix: "+ std::string(ex.what()));
        }
    }

7 Usage Example

#include "BigDataStatMeth.hpp"

// Example usage
auto result = setDiagonalMatrix(...);