replace element in the vector without using loops or if statement

using a logical vector and a single line of code (3 total lines if you count the “function” line and the “end” line). Your function should not have any loops or if statements in it. (You should assume the input is a row vector.)
here is the given code:
function [ y ] = nottwo( v )
y = [];
for i = 1:length(v)
if v(i)~= 2
y = [y, 0];
else
y = [y, 10];
end
end

 採用された回答

Star Strider
Star Strider 2018 年 1 月 25 日

0 投票

It is difficult to help without giving away the solution.
To use a logical vector to address the array, see what this example code is doing:
v = randi(9, 1, 20)
LogicalIndex = v ~= 2
See the documentation on Matrix Indexing (link) for a full discussion.

3 件のコメント

Walter Roberson
Walter Roberson 2018 年 1 月 25 日
Hint: logical vectors can be multiplied by a constant such as 10.
siemcheng ngor
siemcheng ngor 2018 年 1 月 25 日
i tried it but it still give me 1
Star Strider
Star Strider 2018 年 1 月 25 日
Please see the documentation on Matrix Indexing I linked to.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by