Modifying a Variable if a condition is met

19 ビュー (過去 30 日間)
Cody Kessler
Cody Kessler 2021 年 7 月 1 日
コメント済み: Cody Kessler 2021 年 7 月 1 日
I have a 300x1 Matrix, if a value in rows 1:75 is negative I want to add 360 to the negative value, if its positive I want to add 180 to it. There are other conditions similar to this that will be done to values in 76:150, 151:225, 226:300, but once I get started I think I can figure the rest out. I'm fairly new to Matlab so I intially tried an If statement but I couldnt get it to work. Any help would be greatly appreciated

採用された回答

Rik
Rik 2021 年 7 月 1 日
Array operation in Matlab tend to be much faster than other solutions. This is a situation where you can use logical indexing:
%generate some random data
data=randn(30,1)*180;data(data<-180)=-180;data(data>180)=180;
%create copy to show changes later
original=data;
ind=1:5;
tmp=data(ind);
L=tmp<0;
data(ind(L)) = data(ind(L))+360;
L=tmp>0; %NB: tmp is not updated yet, this might not be what you want
data(ind(L)) = data(ind(L))+180;
[original data]
ans = 30×2
36.9248 216.9248 7.8090 187.8090 52.4707 232.4707 84.1838 264.1838 -65.3090 294.6910 -74.6702 -74.6702 -146.6197 -146.6197 164.8950 164.8950 180.0000 180.0000 -180.0000 -180.0000
Using a setup like this allows you to easily create the ind array inside a loop.
If performance is paramount, this is not the optimal solution.
  1 件のコメント
Cody Kessler
Cody Kessler 2021 年 7 月 1 日
Thank You

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by