Addition to specified elements in a vector with for loop to create a new vector

조회 수: 6 (최근 30일)
Hi all,
I am trying to add to specified elements in a vector to create a new one with the new values, however, unfortunately I could not make it...
The addition has been made to all the elements!
clear all;
x=[-7.5 -2.5 2.5 7.5] %
for i=1:3
xx(1,i)=2.5+x(i) % I need the 2.5 added only to [-7.5 -2.5 2.5] and also I need the output to be with the original vector included
% I mean I'd like the output to be
% xx(1,i)= [-7.5 -5 -2.5 0 2.5 5 7.5]
% I know i only = 3 and I need the output to be 9 elements but what can I do ??
end
  댓글 수: 2
Korbinian Volgt
Korbinian Volgt 2019년 11월 8일
편집: Korbinian Volgt 2019년 11월 8일
I am not sure what your exact intention is by +2.5, I guess what you want is to have an equally distributed vector with a step of 2.5 instead of 5. In general it's good practice to predefine vectorlength, so one approach would be:
x=[-7.5 -2.5 2.5 7.5];
xx = zeros(1,7);
for i=1:3
xx(1,2*i-1) = x(1,i);
xx(1,2*i) = x(1,i) + 2.5;
end
xx(1,end) = x(end)
But much easier would be to define your vector as equal distributed numbers from your minimum to the maximum value with the stepsize of 2.5:
xx = -7.5:2.5:7.5
Ali Tawfik
Ali Tawfik 2019년 11월 8일
Hi Korbinian,
actually david has answered what I meant, however,I have been trying to have output of 9 elements because later I will use this vector in plot...
I mean I need some of the elements to be repeated like the following:
[-7.5 -5 -2.5 -2.5 0 2.5 2.5 5 7.5]
Hope you understand, and try to help me!

댓글을 달려면 로그인하십시오.

채택된 답변

David Hill
David Hill 2019년 11월 8일
xx=[x(1:3);x(1:3)+2.5];
xx=[xx(:)',x(4:end)];
  댓글 수: 3
David Hill
David Hill 2019년 11월 8일
What elements to you want repeated? I don't understand what you are trying to do. What are you plotting against?
Ali Tawfik
Ali Tawfik 2019년 11월 9일
Hi,
Thanks for your prompt reply.
I will plot them aganist vector of 9 elements, I would like to repeat element no#: 3 and 6
so it's -2.5 and 2.5.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by