Changing elements in an array

5 ビュー (過去 30 日間)
Elizabeth
Elizabeth 2014 年 4 月 19 日
コメント済み: Image Analyst 2014 年 4 月 19 日
I have an array of L zeros. I'm working on a program that changes the state of the elements (ones to zeros and zeros to ones). The first time through I change every element. The second time through every second element. The third time through every third element and so on to the Lth time.
I'm thinking some type of loop, similar to a Josephus problem. Somehow counting to every nth element, comparing it, and changing it. But I'm not sure of how to change to looking at the next nths (the previous n plus 1) to Lth element each loop.
  1 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 4 月 19 日
Can you post a short example?

サインインしてコメントする。

回答 (1 件)

Image Analyst
Image Analyst 2014 年 4 月 19 日
Do you mean like this:
clc;
vec = randi(2, 1, 30) - 1; % Random array of 1's and zeros.
L = sum(vec==0)
for k = 1 : L-1
selector = 1 : k : length(vec)
vec(selector) = ~vec(selector)
end
  2 件のコメント
Elizabeth
Elizabeth 2014 年 4 月 19 日
This does not start with a zero vector and changes the first element and counts off from there. So when selecting every 3rd element it selects the first then fourth instead of the third then sixth.
Image Analyst
Image Analyst 2014 年 4 月 19 日
So change it to start with zero. No big deal. I assumed that you would already have vec so I just made up something. Don't use mine - use yours.
For the n'th element if you want to start it at element #n, then do so.
selector = n : n : length(vec); % Basic MATLAB concept....

サインインしてコメントする。

カテゴリ

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