how to use abs function in this code?

조회 수: 3 (최근 30일)
Ozan Mirzanli
Ozan Mirzanli 2020년 5월 26일
댓글: Ozan Mirzanli 2020년 5월 26일
%Write a Matlab script to create random integer matrix with elements between -30 and 30.
%The size of the matrix must be first be read from user input. Use loops to sum of each row.
%Then find the differences between all pairs of these sums.
a=input('Enter the size of rows:');
b=input('Enter the size of columns:');
A=randi([-30 30],a,b)
r=zeros(a);
d=zeros(a);
for i=1:a
for j=1:b
r(i)=r(i)+A(i,j);
end
end
for k=1:a
for l=1:a
d(k,l)=(r(k)-r(l));
end
end
difference=triu(d,1)
%So I write this code and it worked -with a problem-. Let's say I created a 2x2 Matrix.
%TheSumOfFirstRow=2, TheSumOfSecondRow=3. As the result I wanna see both 2-3=-1 and 3-2=1.
%But the code that I wrote calculates just 2-3=-1.
Can someone please help :)

답변 (1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 5월 26일
a=input('Enter the size of rows:');
b=input('Enter the size of columns:');
A=randi([-30 30],a,b)
r=zeros(a);
d=zeros(a);
for i=1:a
for j=1:b
r(i)=r(i)+A(i,j);
end
end
for k=1:a
for l=1:a
d(k,l)=abs((r(k)-r(l)));
end
end
difference=triu(d,1)
  댓글 수: 4
Ozan Mirzanli
Ozan Mirzanli 2020년 5월 26일
This is our matrix
A =
-14 9
11 -21
This is the result due to your second code
Difference =
-5 15
15 -5
This is the result how it should be
Difference =
5 (Sum of Row 1 - Sum of Row 2)
-15 (Sum of Row 2 - Sum of Row 1)
The sentences in parantheses are not gonna be in the result, I write them to explain what I exactly mean.
Ozan Mirzanli
Ozan Mirzanli 2020년 5월 26일
any ideas?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by