Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
jake stan
jake stan am 23 Mär. 2018
Kommentiert: Birdman am 23 Mär. 2018
% 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

Akzeptierte Antwort

Birdman
Birdman am 23 Mär. 2018
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 Kommentare
jake stan
jake stan am 23 Mär. 2018
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 am 23 Mär. 2018
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by