row addition on matrix
16 views (last 30 days)
Show older comments
Hello everyone, i got error in my coding , can you please help me.
A=[-0.5000, 2.5000, -4.0000, 5.0000, -3.5000, 2.5000]
B=[2.4217, -0.4930, 0, -0.4217, 0, 0
0, 3.0265, -2.1892, 0, -2.3001, 0
-2.1892, 0, 0, 0, -0.4217, 0.4696
0, 0, 2.4217, -2.3001, 0, -3.6869]
here i want to add row element with each other and gives single row matrix. i.e. C11= 0-2.1892+Aij =-2.1892-0.500=-0.2676 (i have to avoid the element belongs to current value of i and j)
C=[-0.2676, 5.0334, -3.7676, 2.2783, -6.2217, -0.7173]
how can i get this single row matrix using mat lab code? can anyone help me please.
for i=1:4
for j=1:6
sum=0;
for jj=1:6
if H(jj,j)==1 && jj~=i
sum=sum+B(jj,j)
end
end
if H(jj,j)==1 && jj~=i
C(i,j)=sum+A(i,j)
end
end
H=[1 1 0 1 0 0;
0 1 1 0 1 1;
1 0 0 0 1 1;
0 0 1 1 0 1]
where, jj=set of row locations of the H matrix equation
2 Comments
Guillaume
on 4 May 2016
Edited: Guillaume
on 4 May 2016
Please use the formatting tools offered by this forum. There is a {}Code button that will format anything you paste as code.
I've formatted the post for you. Didn't you see that all your matrices appeared all as one line and therefore appeared to be row vectors? Obviously, the answer to your question is different for row vectors and for matrices.
Also, do not use sum for a variable name as it stops you from using the sum function.
Accepted Answer
More Answers (1)
Guillaume
on 4 May 2016
Your jj should go from 1 to 4 or better from 1 to size(H, 1), not 1 to 6. The loops are a complete waste of time in any case.
If you still have the sum variable in your workspace, please clear it otherwise my answer will not work:
clear sum
You say that you want to "avoid the element belongs to current value of i and j" which I understands to mean you don't want the elements on the diagonal (that's what your code appears to do). In that case:
C = A + sum(B .* H .* ~eye(size(B)))
However, your example of C does not do that and is simply:
C = A + sum(B .* H)
Basically, multiply B with H element-wise so only the elements of B you want to keep are non-zero, then use the sum function which sums all the rows together by default and leaves you with just one row. Add that to A.
2 Comments
Guillaume
on 4 May 2016
But, yet the C11 you showed is equal to -0.2676 which is A + B11 + B31 = 0.5 + 2.4217 + -2.1892, so I'm confused.
I you want to ignore the first row of B:
C = A + sum(B(2:end, :) .* H(2:end, :))
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!