array with 1 and -1 - multiply coloums

Hello,
I have an array with a lot of -1 and 1.
Example:
-1 -1 -1 -1 -1
-1 1 -1 -1 -1
1 1 -1 1 -1
-1 -1 1 1 -1
I want to check if the row has 1 and if so if it has more than one 1. If I have more than one 1 in a row I want to multiply the columns for each row with a 1 and write the result into an new array.
For example:
The first row has no 1 > write in the new array 0
The second row has just one 1 in the second column > write the second column into a new array
The third row has a one in the first, second and fourth column > mulitply the three coloums and write the result into the new array
...
Thanks in advance for the answers!

3 件のコメント

Jan
Jan 2022 年 11 月 2 日
What is the wanted output for the posted input? 1 matrix or 3 vectors?
What have you tried so far and which problems occur?
Ma Hel
Ma Hel 2022 年 11 月 3 日
I would be nice to get one matrix.
Jan
Jan 2022 年 11 月 3 日
I assume the problem is solved by Voss' answer. But for your next question: It would be really helpful, if you do not only mention, that it is "one matrix" but post the manually created output for the shown input.

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

 採用された回答

Voss
Voss 2022 年 11 月 2 日

1 投票

Like this?
M = [
-1 -1 -1 -1 -1
-1 1 -1 -1 -1
1 1 -1 1 -1
-1 -1 1 1 -1];
[n,m] = size(M);
new_arrays = repmat({zeros(n,1)},1,n);
for ii = 1:n
idx = M(ii,:) == 1;
if any(idx)
new_arrays{ii} = prod(M(:,idx),2);
end
end
new_arrays{:}
ans = 4×1
0 0 0 0
ans = 4×1
-1 1 1 -1
ans = 4×1
-1 1 1 1
ans = 4×1
1 1 -1 1

2 件のコメント

Ma Hel
Ma Hel 2022 年 11 月 3 日
Thank you very much! This is what I was looking for.
Jan
Jan 2022 年 11 月 3 日
@Voss: I'm impressed! Thanks. I did not even understand the question.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2022 年 11 月 2 日

コメント済み:

Jan
2022 年 11 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by