Function Output Not Displaying
4 views (last 30 days)
Show older comments
Krish Desai
on 27 Sep 2015
Answered: Walter Roberson
on 27 Sep 2015
function output = IsMagic(n)
A= zeros(n);
r=n;
c=n;
row_index = 1;
while row_index <= r
col_index=1;
while col_index <= c
A(row_index,col_index) = randi(1*n.^2);
col_index=col_index + 1;
end
row_index= row_index +1;
end
matrix=A;
columnsum=sum(matrix);
disp ('The sum for the columns is:')
fprintf ('%d,\n', columnsum)
rowsum=sum(matrix,2);
disp ('The sum for the rows isL')
fprintf ('%d,\n', rowsum)
d1=sum(diag(matrix));
d2=sum (diag(flip(A)));
disp ('The sum for the diagonals is')
fprintf ('%d, %d \n',d1,d2)
if numel(unique(columnsum))==1
if numel(unique(rowsum))==1
if numel(unique(d1))==1
if numel (unique(d2))==1
if (columnsum(1)==(rowsum(1))&& (columnsum(1))== (d1(1)) && (columnsum(1))==(d2(1)))
output=1;
else
output=0;
end
end
end
end
end
end
The purpose of this code is to create a function called isMagic. The function takes one input n, creates a square matrix of size n × n using random integers between 1 and n2,and returns the logical value true (1) if the resulting matrix is a magic square and false(0) if it not a magic square.
I have done everything, but for some reason the output is not displaying. What am I doing wrong?
0 Comments
Accepted Answer
Walter Roberson
on 27 Sep 2015
You do not assign output in some cases. You have a series of
if this
if that
if theother
output=1
else
output=0;
end
end
end
Consider what would happen if "this" is not true: it would never get to try "that" and "the other" to assign to output.
One way of handling this is to assign 0 to output before the "if" structure and then only assign 1 in the case you can prove that it is "perfect". In all the other cases output would stay 0 which is what you want.
But you should also look at the "&" and "&&" operators
if this & that & theother
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical 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!