How can I generate values randomly from another existing vecor?

Hi everyone My problem is I want to generate a vector of values from other vector with zeros For example My vector is v1=[122,34,20,5,21] The new vector that I want to get is like that: V2=[122,0,20,0,0,5]

 採用された回答

J. Alex Lee
J. Alex Lee 2021 年 4 月 27 日

1 投票

how about
v1 = [122,34,20,5,21]
v1a = [0,v1]
N = numel(v1a)
ridx = randi(N,size(v1))
v2 = v1a(ridx)

3 件のコメント

Mira le
Mira le 2021 年 4 月 27 日
Is there other solution?, this one doesn't work with a long vector
J. Alex Lee
J. Alex Lee 2021 年 4 月 27 日
how does it fail?
Looking at the error message you posted in your other message I suspect your v1 vector is actually a column vector, not a row vector.
v1 = [1, 2, 3]
v1 = 1×3
1 2 3
v1a = [0, v1]
v1a = 1×4
0 1 2 3
v2 = [1; 2; 3]
v2 = 3×1
1 2 3
v2a = [0; v2]
v2a = 4×1
0 1 2 3
v2bWILLNOTWORK = [0, v2]
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
In v2bWILLNOTWORK, 0 has 1 row and v2 has 3 rows. You can't put them side-by-side in a vector but you can stack them on top of one another as shown with v2a. Compare with v1a, where both 0 and v1 had 1 row and so could be stored side-by-side.
If I'd written v1a with [0; v1] that wouldn't have worked since 0 and v1 don't have the same number of columns.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeGraphics Performance についてさらに検索

製品

リリース

R2017a

タグ

質問済み:

2021 年 4 月 27 日

コメント済み:

2021 年 4 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by