Simple vector question.

조회 수: 14 (최근 30일)
Danny C
Danny C 2016년 9월 6일
답변: Star Strider 2016년 9월 7일
function vec = weave(in1, in2)
a = length(in1);
b = length(in2);
l = max(a,b);
vec = zeros(1, 2.*l);
vec(1:2:2.*a) = in1;
vec(2:2:2.*b) = in2;
I'm trying to create a function that a larger vector where the values in the first vector are inserted in the odd indices and the values in the second vector are inserted in the even indices(weave). The condition is that f the two vectors are not the same length, the shorter vector should be extended by adding consecutive integers to the end. I figured out how to put put those vectors into the position but I couldn't figure out how to extend shorter vector by adding consecutive integers(I could only figure out to fill that with same integers.) What would be the solution?
  • For example, [5 4 1 8 9 1] [7 3 5 5] becomes [5 7 4 3 1 5 8 5 9 6 1 7] instead of [5 7 4 3 1 5 8 5 9 0 1 0].

채택된 답변

Star Strider
Star Strider 2016년 9월 7일
One approach:
in1 = [5 4 1 8 9 1];
in2 = [7 3 5 5];
cin = {in1; in2}; % Create Cell Array For Addressing Convenience
Lin = [length(in1) length(in2)]; % Vector Lengths
Ldif = abs(Lin(1)-Lin(2)); % Length Difference
[~,Lmin] = min(Lin); % Find Vector With Minimum Length
cin{Lmin} = [cin{Lmin} cin{Lmin}(end)+[1:Ldif]]; % Extend Shorter Vector As Desired
vec = zeros(1, 2*max(Lin)); % Preallocate
vec(1:2:end) = cin{1}; % Weave Odd Elements
vec(2:2:end) = cin{2}; % Weave Even Elements
vec =
5 7 4 3 1 5 8 5 9 6 1 7

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Web Services from MATLAB Using HTTP에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by