フィルターのクリア

True false results to be saved as a value

1 回表示 (過去 30 日間)
Dylan Mecca
Dylan Mecca 2018 年 2 月 22 日
編集済み: Stephen23 2018 年 2 月 22 日
I have a vector, a = [1,0,1,1,1,0,0,0......]
I want to say that when a is true, or when the elements in a are equal 1, to make another vector correspond.
So if I wanted the true elements to correspond as .25, how can I make another vector that reads: b = [.25,0,.25,.25,.25,0,0,0.....,]?
I was thinking something along the lines below.
a = zeros(1,10)
b = zeros(size(a))
while a == 1
b = .25
end

採用された回答

Stephen23
Stephen23 2018 年 2 月 22 日
編集済み: Stephen23 2018 年 2 月 22 日
Simplest would be to just multiply the logical vector by 0.25:
>> a = [1,0,1,1,1,0,0,0];
>> b = a*0.25
b =
0.25 0 0.25 0.25 0.25 0 0 0
A more complex but versatile solution would be to convert the logical values into linear indices:
>> c = [0,0.25];
>> c(a+1)
ans =
0.25 0 0.25 0.25 0.25 0 0 0
  3 件のコメント
Stephen23
Stephen23 2018 年 2 月 22 日
編集済み: Stephen23 2018 年 2 月 22 日
If you want to use a loop then you will need to use indexing:
a = [1,0,1,1,1,0,0,0];
b = zeros(size(a));
for k = find(a)
b(k) = .25;
end
or
b = zeros(size(a));
for k = 1:numel(a)
if a(k)
b(k) = .25;
end
end
Jan
Jan 2018 年 2 月 22 日
@Dylan: The while approach does not work. See the documentation:
doc while
while creates a loop until the scalar condition gets false. But a==1 is 1. a vector and 2. a loop does not branch to different commands, such that your problem is not a job for a loop at all. In consequence while is a wrong approach and that Stephen suggests something completely different is the right idea.
A method using a loop would be:
a = [1,0,1,1,1,0,0,0];
b = zeros(size(a));
for k = 1:numel(a)
if a(k)
b(k) = 0.25;
end
end
But Stephen's suggestions are cleaner, easier and faster. +1

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by