Create arrays from single array indexes

1 回表示 (過去 30 日間)
Aravin
Aravin 2015 年 5 月 25 日
編集済み: Stephen23 2015 年 5 月 25 日
Lets say I have array A which contains the some unsigned numbers. The length of A is always even. I have following code which I want to convert into vectorizztion.
A= [10 20 30 50];
output = cell(1, length(A)/2);
j = 1;
for i=1:2:length(A)/2
output(j) = A(i):A(i+1);
j = j + 1;
end
All I want to avoid this loop.
  1 件のコメント
Stephen23
Stephen23 2015 年 5 月 25 日
編集済み: Stephen23 2015 年 5 月 25 日
So this is the code in your original question:
A= [10 20 30 50];
output = cell(1, length(A)/2);
j = 1;
for i=1:2:length(A)/2
output(j) = A(i):A(i+1);
j = j + 1;
end
When I run the code it throws this error:
??? Conversion to cell from double is not possible.
Error in ==> temp at 7
output(j) = A(i):A(i+1);
And if I convert the code so that the variable output uses cell array indexing it generates the following output:
>> output
output =
[1x11 double] []
>> output{1}
ans =
10 11 12 13 14 15 16 17 18 19 20
Is this really what you intended?

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

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 5 月 25 日
out=arrayfun(@(x) A(x):A(x+1),1:numel(A)/2,'un',0)
But this is not faster then a for loop

Stephen23
Stephen23 2015 年 5 月 25 日
編集済み: Stephen23 2015 年 5 月 25 日
Perhaps you intended it to do something like this:
>> A = [10 20 30 50];
>> B = arrayfun(@(b,e)b:e, A(1:2:end), A(2:2:end), 'UniformOutput',false)
B =
[1x11 double] [1x21 double]
>> B{1}
ans =
10 11 12 13 14 15 16 17 18 19 20
>> B{2}
ans =
Columns 1 through 16
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
Columns 17 through 21
46 47 48 49 50

Walter Roberson
Walter Roberson 2015 年 5 月 25 日

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by