필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
matthew gaskins
matthew gaskins 2017년 3월 24일
편집: Iddo Weiner 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
Iddo Weiner 2017년 3월 24일
편집: 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
disp('invalid answer')
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

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by