# How do i start my code over if i'm doing data validation?

1 ビュー (過去 30 日間)
matthew gaskins 2017 年 3 月 24 日

I'm doing data validation within my code for homework. I'm typing a code that determines if a matrix is a magic-square. On a requirement sum of rows and cols must be equal but if they're not I'm supposed to ask user if they would like to try again. And if so, The matrix they entered needs to go through the entire code again for other data validation checks.

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

### 回答 (1 件)

Iddo Weiner 2017 年 3 月 24 日

Wouldn't the sum of rows always equal the sum of cols in any matrix? See this link for discussion on determining whether a matrix is magic or not:
Anyway, here's a code that technically does what you ask. When you use rand() as input it will sometimes fail to recognize that the sum of rows and cols is equal becasue of the way MATLAB handles floating point variables:
function out = is_magic(matrix)
while true
if sum(sum(matrix)) == sum(sum(matrix,2))
out = 1;
break
else
while true
ANS = input('this matrix wasn''t magic. Would you like to try again? Y/N ','s');
if strcmpi(ANS,'Y')
matrix = input('insert new matrix:');
break
elseif strcmpi(ANS,'N')
out = 0;
return
else
end
end
end
end
Here's a usage example:
>> is_magic(rand(3,4))
this matrix wasn't magic. Would you like to try again? Y/N Y
insert new matrix:magic(5)
ans =
1
>> is_magic(rand(3,4))
this matrix wasn't magic. Would you like to try again? Y/N N
ans =
0

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

### Community Treasure Hunt

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

Start Hunting!