フィルターのクリア

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

2 ビュー (過去 30 日間)
jake stan
jake stan 2018 年 3 月 23 日
コメント済み: Birdman 2018 年 3 月 23 日
% 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by