本文介绍了一个C ++数组的matlab风格索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下matlab惯用法的最有效的c ++实现是什么。



假设我在matlab,x,y和idx中有3个向量。

  x = [13,2,5.5,22,107] 
y = [-3,100,200]
idx = [1,2,5]

我要将x的位置1,2和5替换为y的内容。在matlab中,我做

  x [idx] = y 

在c ++中最好的做法是什么?

解决方案

图书馆可能是最接近的,因为它的目标之一是使事情容易的人习惯到Matlab。



下面是一个简短示例(和 uvec 是unsigned ints的向量的typdef)

  //将X的四个特定元素设置为1 
uvec indices;
indices<< 2<< 3<< 6<< 8;

X.elem(indices)= ones< vec>(4);

显然,右侧可以是与索引维度相同的任何其他向量。 / p>

但是,你不能克服的语言约束限制很少:




  • (你可以改变,但很少C / C ++程序员会认为这是一个好主意)

  • 某些操作符,包括 [


I would like to know what the most efficient c++ implementation of the following matlab idiom is.

Suppose I have 3 vectors in matlab, x, y and idx.

x = [13,2,5.5,22,107]
y = [-3,100,200]
idx = [1,2,5]

I want to replace positions 1,2 and 5 of x with the contents of y. In matlab I do

x[idx] = y

What is the best way to do this in c++?

解决方案

The Armadillo library probably comes closest as one of its goals is to make things easy for folks used to Matlab.

Here is a short example (and uvec is a typdef for vector of unsigned ints)

// set four specific elements of X to 1
uvec indices;
indices << 2 << 3 << 6 << 8;

X.elem(indices) = ones<vec>(4);

Obviously, the right-hand side could be any other vector of the same dimension as the index.

But there are few language-imposed constraints you cannot overcome:

  • zero-based indexing at the C++ level (which you could alter, but few C / C++ programmers will consider it a good idea)
  • certain operators, including [

这篇关于一个C ++数组的matlab风格索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 09:25