How do I add a value to an adjacent element without for loop

2 次查看(过去 30 天)
% x = zeros(1,7)
x(1) = 3
x(2) = 4
lengthofx = length(x)
x(3:end) = x(2:end-1)+1
I was wondering how to add a value to a next element without for loop? I'm given x(1) = 3, and x(2) is 4, and
I'm trying to add one to the next element so add 1 to element 3, then add 1 to element 3, and so on but this part
doesn't work: x(2:end) = x(1:end-1)+1.
It adds one to element 3 which becomes 5, but then when it reaches to element 4 it just adds 1 to it, so the element value is one instead of 6

采纳的回答

Birdman
Birdman 2018-3-23
Try this:
x=zeros(1,7);
x(1)=3;
x(2)=4;
x(find(x==0,1,'first'):end)=x(find(x~=0,1,'last'))+1:x(find(x~=0,1,'last'))+sum(x==0)
  5 个评论
jake stan
jake stan 2018-3-23
Oh it doesn't work when I want to change the addition value, so instead of adding one it adds like 6 or any number
Birdman
Birdman 2018-3-23
Ok, try this: By changing N, you will add any value you want,
x=zeros(1,9);
x(1)=3;
x(2)=4;
N=6
x(find(x==0,1,'first'):end)=(x(find(x==0,1,'first'))+1:N:N*(x(find(x==0,1,'first'))+sum(x==0)))+x(find(x~=0,1,'last'))-1+N

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by