From 302055db861c9adc1a96604f59b990dd4ea9ff2d Mon Sep 17 00:00:00 2001 From: Jiri Pittner Date: Mon, 9 Mar 2026 17:10:58 +0100 Subject: [PATCH] tensor: subtensor1() --- t.cc | 22 +++++++++++++++++++++- tensor.cc | 20 ++++++++++++++++++++ tensor.h | 3 +++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/t.cc b/t.cc index 87ac680..81212c0 100644 --- a/t.cc +++ b/t.cc @@ -1084,7 +1084,7 @@ NRMat > b=exp(a); cout < t1 = t.subtensor1(2); +cout < +Tensor Tensor::subtensor1(int i) const +{ +int ind=shape.size(); +if(ind==0) laerror("subtensor of a scalar"); +--ind; +if(shape[ind].number>1) laerror("last index must be standalone in subtensor1"); +i -= shape[ind].offset; +if(i<0||i>=shape[ind].range) laerror("index out of range in subtensor1"); +if(ind==0) return Tensor(data[i]); //results is a scalar +NRVec newshape = shape.subvector(0,ind-1); +Tensor r(newshape); +memcpy(&r.data[0],&data[i*cumsizes[ind]],cumsizes[ind]*sizeof(T)); +if(is_named()) r.names = names.subvector(0,ind-1); +return r; +} + + + + template class Tensor; template class Tensor >; template std::ostream & operator<<(std::ostream &s, const Tensor &x); diff --git a/tensor.h b/tensor.h index 52cb35f..2a2fc9c 100644 --- a/tensor.h +++ b/tensor.h @@ -276,6 +276,9 @@ public: Tensor(int xrank, const NRVec &xshape, const NRVec &xgroupsizes, const NRVec xcumsizes, const NRVec &xdata) : myrank(xrank), shape(xshape), groupsizes(xgroupsizes), cumsizes(xcumsizes), data(xdata) {}; Tensor(int xrank, const NRVec &xshape, const NRVec &xgroupsizes, const NRVec xcumsizes, const NRVec &xdata, const NRVec &xnames) : myrank(xrank), shape(xshape), groupsizes(xgroupsizes), cumsizes(xcumsizes), data(xdata), names(xnames) {}; + //subtensor - todo: more general versions + Tensor subtensor1(int i) const; //for one value of rightmost index + //conversions from/to matrix and vector explicit Tensor(const NRVec &x); explicit Tensor(const NRMat &x, bool flat=false);