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

3 visualizzazioni (ultimi 30 giorni)
matthew gaskins il 24 Mar 2017
Modificato: Iddo Weiner il 24 Mar 2017
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.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (1)

Iddo Weiner il 24 Mar 2017
Modificato: Iddo Weiner il 24 Mar 2017
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
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Text Data Preparation in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by