replace the elements of a vector with an element sequence

1 回表示 (過去 30 日間)
pavlos
pavlos 2014 年 3 月 5 日
コメント済み: pavlos 2014 年 3 月 6 日
Hello,
Consider a 100x1 matrix with random values from 1 to 3.
How can replace all the values with an element sequence of 4 elements, such as:
all 1 with 0100
all 2 with 1001
all 3 with 0001
Thank you.
Best,
Pavlos

採用された回答

Andrei Bobrov
Andrei Bobrov 2014 年 3 月 5 日
編集済み: Andrei Bobrov 2014 年 3 月 5 日
A = [0 1 0 0;1 0 0 1;0 0 0 1];
B = randi(3,100,1);
out = A(B,:);
for negative values:
B2 = [-1 -0.5 -0.25];
[l0,ii] = ismember(B,B2);
out = nan(numel(B),size(A,2));
idx = ii(l0);
out(l0,:) = A(idx,:);
  2 件のコメント
pavlos
pavlos 2014 年 3 月 5 日
Hello,
How can I do the same if the 100x1 matrix contains negative values.
For example, instead of 1, 2, 3 consider -1, -0.5, -0.25
Thank you.
Andrei Bobrov
Andrei Bobrov 2014 年 3 月 5 日
Please see answer by Jos

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 3 月 5 日
% values V(k) in B should be mapped to row A(k,:)
A = [0 1 0 0;1 0 0 1;0 0 0 1]
V = [-1 -0.5 -0.25]
B = [-1 -0.5 -1 -0.25 -1 -0.25 -0.5 -1 -1]
[~,k] = ismember(B,V)
out = A(k,:)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by