フィルターのクリア

How do I populate a column with a constant value?

60 ビュー (過去 30 日間)
balsip
balsip 2016 年 6 月 21 日
コメント済み: Star Strider 2016 年 6 月 21 日
I am trying to populate a column in a newly created empty variable (ConstantVector) with a constant value for the column length of an existing vector (Vector_A), which is 5904x1.
The following code populates a row (1x5904):
ConstantVector=[];
for i=1:length(Vector_A)
ConstantVector(i)=((10^5)/((8.31434)*(298.15)))*(10^6);
end
How should I be coding this so that the ConstantVector is one column with the same value in the length of Vector_A?

採用された回答

Star Strider
Star Strider 2016 年 6 月 21 日
Use the ones function to create a vector of 1 and then multiply it by your constant value:
ConstantVector = ones(size(VectorA))*((10^5)/((8.31434)*(298.15)))*(10^6);
  2 件のコメント
balsip
balsip 2016 年 6 月 21 日
Thank you, Star Strider! That does the trick, and without a for loop, too.
Star Strider
Star Strider 2016 年 6 月 21 日
My pleasure!

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2016 年 6 月 21 日
Depending what you're planning to do with the resulting vector. One obvious possibility is repmat.
x = magic(5);
y = repmat(pi, size(x));
z = repmat(42, size(x, 1), 1);
w = repmat(-999, 2, size(x, 2));
If you need to add the constant to the original, like if I wanted to add to the vector z, take advantage of scalar expansion rather than creating a (potentially large) temporary array.
q1 = z + 1;
q2 = z + ones(size(z));
isequal(q2, q2) % returns true
The repelem and bsxfun functions may also be of interest, again depending on what you're trying to do.
  1 件のコメント
balsip
balsip 2016 年 6 月 21 日
Pretty sure your solution would help me, too, Steven. I have a four-term formula (not shown) where two of the terms are variable time series from my data set and the other two terms are constant values.
I'm a little surprised that I need to create a vector of a certain length for a constant value. Maybe you're showing me a way around this, but the first answer above is a bit easier to wrap my head around.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by