homework ,matrix and avg

hi,my ex is to check the first diag and the secondary if they even ,and check the avg of those who are even.this is my work until now,i have problems with syntax.anyone can help me finish it?
n=randi(6);
a=randi(100,n,n);
b=eye(2,length(a));
b(1,:)=diag(a);
b(2,:)=diag(rot(a));
for (i=1:1:length(b))
{
if((mod(b(i),2)==0));
{ j++;
x=x+b(i);
}
else i++;
}
avg=x/j;

Risposte (1)

Image Analyst
Image Analyst il 17 Set 2017

0 voti

Step 1 is to get rid of any { and replace any } with the word "end". Then replace i++ with i=i+1 and j++ with j=j+1. You will also need to initialize x before the for loop. Start with that and see how much further you can go.

3 Commenti

yuval ohayon
yuval ohayon il 17 Set 2017
Modificato: Walter Roberson il 17 Set 2017
clear
clc
n=randi(6);
a=randi(100,n,n);
b=eye(2,length(a));
b(1,:)=diag(a);
b(2,:)=diag(rot90(a));
x=0;
for i=1:1:length(b)
if((mod(b(i),2)~=0));
j=j+1;
x=x+b(i);
else i=i+1;
end
end
avg=x/j;
well the program works but my targets aren't, how the hell avg become complex number, help
The complex value for ‘avg’ is the result of ‘i’ and ‘j’ being defined in MATLAB as imaginary operators equal to sqrt(-1) unless they are previously defined as being real numbers.
To illustrate:
j=j+1
j =
1 + 1i
Image Analyst
Image Analyst il 17 Set 2017
b is a 2 by 6 array. So why are you passing only one index into it instead of 2?
DO NOT assign i to something inside the loop. It's bad practice. The poorly-named "i" will be assigned automatically by the "for" statement and you should not override that, or else trouble and confusion will ensue.
Do not call your variable "j" - another poor choice as Star said. Call your variables descriptive names like "numberOfEvens" or something. Certainly don't call them i or j or any name of a built in function like "sum"!

Accedi per commentare.

Categorie

Scopri di più su MATLAB in Centro assistenza e File Exchange

Richiesto:

il 17 Set 2017

Modificato:

il 17 Set 2017

Community Treasure Hunt

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

Start Hunting!

Translated by