How to substitute one value in vector by vector?

8 ビュー (過去 30 日間)
Premysl Stastny
Premysl Stastny 2021 年 9 月 23 日
回答済み: Matt J 2021 年 9 月 23 日
Hello,
I have got a vectro x=(-1 1 -1 1) and I need to replace positions containing -1 for a vector (1 2 3) and positions containing 1 for a vector (3 2 1). so the result should be x=(1 2 3 3 2 1 1 2 3 3 2 1).
Could somebody help me?
Thanks a lot

採用された回答

KSSV
KSSV 2021 年 9 月 23 日
編集済み: KSSV 2021 年 9 月 23 日
x=[-1 1 -1 1] ;
iwant = cell(1,length(x)) ;
for i = 1:length(x)
if x(i) == -1
iwant{i} = [1 2 3 ];
elseif x(i) == 1
iwant{i} = [3 2 1] ;
end
end
iwant = cell2mat(iwant)
iwant = 1×12
1 2 3 3 2 1 1 2 3 3 2 1
%% No loop
% No loop
x=[-1 1 -1 1] ;
iwant = cell(1,length(x)) ;
iwant(x==1) = {[3 2 1]} ;
iwant(x==-1) = {[1 2 3]} ;
iwant = cell2mat(iwant)

その他の回答 (4 件)

Matt J
Matt J 2021 年 9 月 23 日
編集済み: Matt J 2021 年 9 月 23 日
x=[-1 1 -1 1];
idx=(x==1);
X=nan(3,numel(x));
X(1,idx)=3;
X(2,idx)=2;
X(3,idx)=1;
X(:,~idx)=4-X(:,idx);
X=X(:).'
X = 1×12
1 2 3 3 2 1 1 2 3 3 2 1

Matt J
Matt J 2021 年 9 月 23 日
x=[-1 1 -1 1];
i=(x+3)/2;
V=[1 2 3;3 2 1].';
X=reshape( V(:,i) ,1,[])
X = 1×12
1 2 3 3 2 1 1 2 3 3 2 1

Matt J
Matt J 2021 年 9 月 23 日
x=[-1 1 -1 1];
x=strrep(10*x,10,[3,2,1]);
Warning: Inputs must be character vectors, cell arrays of character vectors, or string arrays.
x=strrep(x,-10,[1,2,3])
Warning: Inputs must be character vectors, cell arrays of character vectors, or string arrays.
x = 1×12
1 2 3 3 2 1 1 2 3 3 2 1

Matt J
Matt J 2021 年 9 月 23 日
x=[-1 1 -1 1];
X=kron(-x,[1,2,3]);
X=X+4*(X<0)
X = 1×12
1 2 3 3 2 1 1 2 3 3 2 1

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by