2009-04-28 88 views
6

是否有一個單一的表達方式來分配一個標量到升壓矩陣或向量的所有元素?我試圖找到代表的更緊湊的方式:填充升壓矢量或矩陣

boost::numeric::ublas::c_vector<float, N> v; 
for (size_t i=0; i<N; i++) { 
    v[i] = myScalar; 
} 

下不起作用:

boost::numeric::ublas::c_vector<float, N> 
    v(myScalar, myScalar, ...and so on..., myScalar); 

boost::numeric::ublas::c_vector<float, N> v; 
v = myScalar; 
+0

你也應該標記這個 「C++」。 – TonJ 2009-04-28 15:09:49

+0

好點。完成。 – 2009-04-28 15:29:02

回答

7

因爲向量建模一個標準的隨機存取容器,所以你應該能夠使用標準的STL算法。喜歡的東西:

c_vector<float,N> vec; 
std::fill_n(vec.begin(),N,0.0f); 

std::fill(vec.begin(),vec.end(),0.0f); 

這可能也與Boost.Assign兼容的,但你必須檢查。

0

去過,因爲我用C++一段時間。以下工作?

for (size_t i = 0; i < N; v[i++] = myScalar) ; 
+0

這會工作,但它是相對於表達一個完整的聲明。 – 2009-04-28 14:51:21

+0

的確如此,但它是更緊湊的方式,這就是你想在帖子中找到的東西。 – 2009-04-28 14:54:40

+0

是的,因此+1。 – 2009-04-28 15:29:44

6

我已經開始使用boost::assign的,我想靜態分配特定值(從上面的鏈接解除實例)的情況。

#include <boost/assign/std/vector.hpp> 
using namespace boost::assign; // bring 'operator+()' into scope 

{ 
    vector<int> values; 
    values += 1,2,3,4,5,6,7,8,9; 
} 

您還可以使用boost::assign的地圖。

#include <boost/assign/list_inserter.hpp> 
#include <string> 
using boost::assign; 

std::map<std::string, int> months; 
insert(months) 
     ("january", 31)("february", 28) 
     ("march",  31)("april", 30) 
     ("may",  31)("june",  30) 
     ("july",  31)("august", 31) 
     ("september", 30)("october", 31) 
     ("november", 30)("december", 31); 

可以允許做list_of()map_list_of()

#include <boost/assign/list_of.hpp> // for 'list_of()' 
#include <list> 
#include <stack> 
#include <string> 
#include <map> 
using namespace std; 
using namespace boost::assign; // bring 'list_of()' into scope 

{ 
    const list<int> primes = list_of(2)(3)(5)(7)(11); 
    const stack<string> names = list_of("Mr. Foo")("Mr. Bar") 
             ("Mrs. FooBar").to_adapter(); 

    map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6); 

    // or we can use 'list_of()' by specifying what type 
    // the list consists of 
    next = list_of< pair<int,int> >(6,7)(7,8)(8,9); 

} 

也有功能repeat()repeat_fun()直接分配和range()它允許你添加重複的值或值的範圍。

1

你試過嗎?

的uBLAS :: c_vector V = uBLAS庫:: scalar_vector(N,myScalar);

5

推薦的方法是這樣的:

boost::numeric::ublas::c_vector<float, N> v; 
v = boost::numeric::ublas::zero_vector<float>(N); 
v = boost::numeric::ublas::scalar_vector<float>(N, value); 

這同樣適用於矩陣類型:

boost::numeric::ublas::matrix<float> m(4,4); 
m = boost::numeric::ublas::identity_matrix<float>(4,4); 
m = boost::numeric::ublas::scalar_matrix<float>(4,4); 
m = boost::numeric::ublas::zero_matrix<float>(4,4);