convert a double array to something like logical

Hello. I want to concert every
1-> 1 0 0 0 0 0 0
2-> 0 1 0 0 0 0 0
3-> 0 0 1 0 0 0 0
4-> 0 0 0 1 0 0 0
5-> 0 0 0 0 1 0 0
6-> 0 0 0 0 0 1 0
7-> 0 0 0 0 0 0 1
example: I have a vector A=[1;5;7;4]; I want it to be S= [
1 0 0 0 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 0 1
0 0 0 1 0 0 0];
Is it possible to do this without for loop? Thanks

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 10 月 15 日
編集済み: Azzi Abdelmalek 2013 年 10 月 15 日

0 投票

A=[1;5;7;4];
B=zeros(numel(A),max(A))
B(sub2ind(size(B),(1:numel(A))',A))=1
Vivek Selvam
Vivek Selvam 2013 年 10 月 15 日
編集済み: Vivek Selvam 2013 年 10 月 21 日

0 投票

Hi Theodor,
You can try a look-up table like this:
lut = logical(diag(ones(1,7)));
A = [1 5 7 4]';
S = lut(A(:),:);
hayim
hayim 2014 年 1 月 13 日

0 投票

Late to the party, but how about this?
A = [1 5 7 4]';
S = bsxfun(@eq,A,1:7)
ans =
1 0 0 0 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 0 1
0 0 0 1 0 0 0
bsxfun is your friend!

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

タグ

質問済み:

2013 年 10 月 15 日

回答済み:

2014 年 1 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by