insert matrix index to specific number

I have zeros matrix A = zeros(1,10);
and I want insert specific number to index range.
ex) index = [1 6 10]; value = [4 6];
I want return the matrix ans = [4 4 4 4 4 4 6 6 6 6];
How can I return this answer not using 'for';

回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2017 年 3 月 3 日

1 投票

my small contribution
index = [1 6 10];
value = [4 6];
ii = zeros(index(end),1);
ii([1,index(2:end-1)+1]) = 1;
A = value(cumsum(ii));

2 件のコメント

Jan
Jan 2017 年 3 月 3 日
+1: I'd prefer this and guess, it is the fastest solution.
Walter Roberson
Walter Roberson 2017 年 3 月 3 日
This assumes that index(1) is 1.
It is an interesting approach, though.

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

Walter Roberson
Walter Roberson 2017 年 3 月 3 日

0 投票

A(index(1):index(end)) = repelem( value, [index(2)-index(1)+1,diff(index(2:end))]);
Stephen23
Stephen23 2017 年 3 月 3 日
編集済み: Stephen23 2017 年 3 月 3 日

0 投票

For MATLAB versions without repelem (pre R2015a):
>> index = [1 6 10]; value = [4 6];
>> cell2mat(arrayfun(@(d,v)repmat(v,1,d),diff(index),value,'Uni',0))
ans =
4 4 4 4 4 6 6 6 6

2 件のコメント

Walter Roberson
Walter Roberson 2017 年 3 月 3 日
Notice though that you output five 4's when the desired output is six 4's. The pattern appears to be that the first index gives a starting position number, that the next gives the ending position number of the first value, that the next after that gives the ending position number of the second value, and so on. The number of repeats of the first item is special, which is why I ended up using [index(2)-index(1)+1,diff(index(2:end))]
Stephen23
Stephen23 2017 年 3 月 3 日
編集済み: Stephen23 2017 年 3 月 3 日
@Walter Roberson: thank you for fixing that strange inconsistency in the index definition. Applying your fix:
>> index = [1 6 10]; value = [4 6];
>> idx = [index(2)-index(1)+1,diff(index(2:end))];
>> cell2mat(arrayfun(@(d,v)repmat(v,1,d),idx,value,'Uni',0))
ans =
4 4 4 4 4 4 6 6 6 6

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

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2017 年 3 月 3 日

編集済み:

2017 年 3 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by