Creating a matrix using the colon function

6 ビュー (過去 30 日間)
Amirhossein Moosavi
Amirhossein Moosavi 2020 年 7 月 19 日
回答済み: John D'Errico 2020 年 7 月 19 日
Hi everyone,
Let us assum that I have two arrays as follows:
A = [1 2 3 4 5]
B = [3 4 5 6 7]
I want to use colon funcion to create Matrix C:
C = [1 2 3
2 3 4
3 4 5
4 5 6
5 6 7]
I used the folloing function, but it does not work. I can use a loop to create this matrix, but I want to know what is the fastest solution. Any idea?
[1 2 3 4 5]: 1: [3 4 5 6 7]
Thanks,
Amir

採用された回答

John D'Errico
John D'Errico 2020 年 7 月 19 日
An array in MATLAB NEEDS to be rectangular. That is a given.
So if the increment is ALWAYS 1 between elements, then the second vector must always be some integer constant greater than the first, for ALL elements. In this case, the difference is 2.
A = [1 2 3 4 5];
B = [3 4 5 6 7];
B - A
ans =
2 2 2 2 2
Given that, it is trivial to generate the result you ask for, (AND it is efficiently done too.)
C = A(:) + (0:2)
C =
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
The above works as long as you have release R2016b or later. Earlier releases would efficiently use
C = bsxfun(@plus,A(:),0:2)
C =
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
As you should see, the first solution is much cleaner and easier to read.
If some elements of B were not uniformly 2 greater than the corresponding element in A, then you would need to decide how to deal with it, since arrays in MATLAB are rectangular. You might decide to zero pad, or insert NaNs or use a cell array to store the results.

その他の回答 (2 件)

madhan ravi
madhan ravi 2020 年 7 月 19 日
No other fastest way , there’s arrayfun() I could think of but I don’t think any faster. I have also submitted feature request regarding this , let’s see what the future holds.

madhan ravi
madhan ravi 2020 年 7 月 19 日
ix = max(diff([A;B]));
c = cumsum([A;ones(ix, numel(A))]).'; % if the difference between each A and B elements are the same , this would be the last step
Wanted = c .* (c <= B(:))
  1 件のコメント
madhan ravi
madhan ravi 2020 年 7 月 19 日
編集済み: madhan ravi 2020 年 7 月 19 日
You will have to compare the timings , I didn’t check it. Still I bet the loop is the eifficient one.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by