Is this the correct syntax for replacing a specific element in a dependent vector?

1 回表示 (過去 30 日間)
numElem = 9990;
w = linspace(2*pi,2*pi*10^18,numElem);
wRes = 2*pi*10^9;
for n = 1:numElem
if w(n) > wRes
w = [w(1:n), wRes, w(n:numElem)];
end
end
freq = w ./ (2*pi);
lambda = 299792458 ./ freq;
if w == wRes
B = 2*pi./lambda;
else
B = pi/2 .*w./wRes;
end
I am trying to create a range of w's and make sure that a specific value, wRes is in there. For that specific wRes, I want an exceptional value for B. Is the above code the correct way of going about it?

採用された回答

Walter Roberson
Walter Roberson 2016 年 12 月 27 日
Note that if you are trying to replace values > wRes with wRes, then another way of doing that is:
w = min(w, wRes);
  1 件のコメント
Real Name
Real Name 2016 年 12 月 28 日
I figured it out, my code was really bad. I had meant to insert wRes into a sorted vector and keep the order.

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

その他の回答 (1 件)

Brendan Hamm
Brendan Hamm 2016 年 12 月 27 日
It looks like you are trying to change any values of w which are greater than wRes to be wRes instead, but you are instead placing an additional element into w at the (n+1)th position and then at the next iteration checking if that value is greater than wRes. I think what you are looking for is logical indexing.
idx = w > wRes;
The ith index of idx is true (1) if w(i) > wRes. Now you can use this to access the elements of w where idx is true and change only those values:
w(idx) = wRes;
Consider this on a simpler example:
x = 1:10;
idx = x > 5; % 6th through 10th elements are true!
x(idx) = -1; % 6th through 10th elements are now -1!

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by