How to change values in an array based on certain rules?
    3 ビュー (過去 30 日間)
  
       古いコメントを表示
    
    Ryan Fedeli
 2019 年 3 月 5 日
  
    
    
    
    
    回答済み: Yasasvi Harish Kumar
      
 2019 年 3 月 6 日
            I have an array and I want to change it so that all entries are zero except each first appearing 1 and -1.
But also, the first nonzero entry needs to be a +1.
I've been trying to use a for loop with if statements to accomplish this, but I can't figure out what rules would be used.
The result should be this:
x = [-1 0 0 1 1 0 1 -1 -1 -1 0 1 1 1 0 0 1 -1 0 0 -1 1 0 0 -1 0] %  change this array to...
xx= [ 0 0 0 1 0 0 0 -1  0  0 0 1 0 0 0 0 0 -1 0 0  0 1 0 0 -1 0] % this
%     ^     ^        ^         ^            ^        ^      ^
%     |  % all of these are the only ones that remain - they alternate between 1 and -1
%     |
% and here the -1 from x is eliminated because there is no preceding +1
% the array x is randomly generated to be a -1, 0, or a 1
Any insight would be appreciated... thank you
0 件のコメント
採用された回答
  Yasasvi Harish Kumar
      
 2019 年 3 月 6 日
        Hi,
Something like this should fix your problem.
f = 1;
for  i = 1:length(x)
    if x(i) == f
        xx(i) = f;
        f = -f;
    else
        xx(i) = 0;
    end
end
Regards
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
				Help Center および File Exchange で Operators and Elementary Operations についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

