Convert vector to matrix with used-defined step

6 ビュー (過去 30 日間)
santos666
santos666 2013 年 9 月 24 日
Hi.
I want to convert a vector to a matrix but with a step defined by me.
For example:
myVector = [1 2 3 4 5 6];
myMatrix = [1 2; 2 3; 3 4; 4 5; 5 6];
I am familiar with vec2mat but this function does not do what I want.
Using this function to create a 2-column matrix the final result would be:
myMatrix = [1 2; 3 4; 5 6];
I already searched but I couldn't find an answer to this problem.
I am trying to avoid using for loops.
Thank you.
Best Regards.

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 24 日
編集済み: Azzi Abdelmalek 2013 年 9 月 24 日
v=[1 2 3 4 5 6];
v=[v;v];
v=reshape(v(2:end-1),2,[])'
%or simply
v=[1 2 3 4 5 6];
v=[v(1:end-1); v(2:end)]'

dpb
dpb 2013 年 9 月 24 日
Think storage order... :)
One (of many possible) solutions...
>> V = [1 2 3 4 5 6];
>> reshape([V(1) reshape([V(2:end-1)' V(2:end-1)']',1,[]) V(end)],2,[])'
ans =
1 2
2 3
3 4
4 5
5 6
>>

santos666
santos666 2013 年 9 月 24 日
編集済み: santos666 2013 年 9 月 24 日
Thank you.
You are both right but i realize now that i gave an example too much simple.
Sorry, my mistake.
An harder one:
if true
v = 1:10
m = [
1 2 3 4 5;
2 3 4 5 6;
3 4 5 6 7;
4 5 6 7 8;
5 6 7 8 9;
6 7 8 9 10;
]
end

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by