How to create a matrix using conditional statements in a loop based in another matrix

Hello,
I have a matrix and I want to generate another matrix according to their elements using a loop.
If one ore more elements of a row is ==0 the correspondent row in the new matrix need to be 0.
If not, it needs to be the sum of the elements in the row.
Comb = % The initial matrix
0 0
4.303 0
2.68 0
0 1.705
4.303 1.705
2.68 1.705
% I need this output:
H = [0
0
0
0
6.008
4.385]
I started with this loop:
for i = 1:size(Comb, 1)
for j = 1:size(Comb, 2)
x = (sum(Comb'))'
if abs(Comb(i,j)) == 0
end
end
end
But it gives that:
x =
0
4.303
2.68
1.705
6.008
4.385
I do not know what insert on the if to display zeros when one element of the row is equal to zero.
Could you help me ?
Thans in advance !

 採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 3 月 20 日
H = all(Comb,2).*sum(Comb,2);

その他の回答 (2 件)

madhan ravi
madhan ravi 2019 年 3 月 20 日
編集済み: madhan ravi 2019 年 3 月 20 日
H=zeros(size(Comb,1),1);
idx=any(Comb,2);
H(idx)=sum(Comb(idx,:),2)

4 件のコメント

Rachel Sabioni
Rachel Sabioni 2019 年 3 月 20 日
Hi Madhan,
Thank you for your response.
I am still have troubles. When I insert your code it keeps showing the same of before:
>> H=zeros(size(Comb,1),1);
idx=any(Comb,2);
H(idx)=sum(Comb(idx,:),2)
H =
0
4.303
2.68
1.705
6.008
4.385
If there is zero on the first or second column of Comb matrix, I need that the result of H is = 0.
Do you know how to deal with that ?
I have no idea why you get the result, I got the result as your expected output. Try
clear all
at the beginning and try again just try the answer I gave.
Ah messed up with any() , use
all(Comb,2)
Rachel Sabioni
Rachel Sabioni 2019 年 3 月 22 日
Thank you so much Madhan. Now it worked ! =)

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

Joel Newton
Joel Newton 2019 年 10 月 10 日
編集済み: Joel Newton 2019 年 10 月 10 日

0 投票

Hi, i wish to make a new matrix from the one below such that if the difference between elements in the second and third row is plus or minus 2 return a value of the mid point in each element of the new matrix. if the difrrence is more than 2 then keep the values from the old matrix in the new matrix.
orginal data =
1 1 1 1
10 10 10 9
14 11 14 11
new matrix should look like this =
1 1 1 1
10 10.5 10 10
14 10.5 14 10
my data set has multiple rows of this 3 block of values (if that makes sense), how do I then iterate down for the rest of the data?
Thanks!

1 件のコメント

Andrei Bobrov
Andrei Bobrov 2019 年 10 月 10 日
Hi Joel! Please ask your question through the menu tab ('Ask' tab).
arrow.png

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

カテゴリ

ヘルプ センター および 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