green
green

Reputation: 713

How to loop for desired output?

HI everyone I have a matrix input program as shown below. However I fail to loop for empty or complex or NaN input. I had tired various kind of method but is still not work. Sincerely hope to get advice from you all in order to solve this problem.

clear;clc
m=2;
for i = 1:m
    for j = 1:m;

        element_A = ['Enter the element in row ' num2str(i) ', col ' num2str(j) ': '];
        A(i,j) = input(element_A);

        while  isnan(A(i,j)) || ~isreal(A(i,j)) || isempty(A(i,j))
            fprintf('Input not valid')
            element_A = ['Enter the element in row ' num2str(i) ', col ' num2str(j) ': '];
            A(i,j) = input(element_A);
        end        

    end
end

%% sample loop
m = str2double( input('??? : ', 's') );
while isnan(m) || ~isreal(m) || m<0
    m = str2double( input('Enter valid value : ', 's') );
end

Upvotes: 0

Views: 90

Answers (1)

HebeleHododo
HebeleHododo

Reputation: 3640

You should be checking for NaN, complex values and empty inputs before you assign them in A. You can do it like this:

m=2;
A = zeros(m); % You do not have to do this but it will increase the performance of your code.
for idx = 1:m
    for jdx = 1:m;
        element_A = ['Enter the element in row ' num2str(idx) ', col ' num2str(jdx) ': '];
        inputElement = input(element_A);
        while isempty(inputElement) || isnan(inputElement) || ~isreal(inputElement)
            fprintf('Invalid input');
            inputElement = input(element_A);

        end
        A(idx,jdx) = inputElement;
    end
end

Notice that I moved isempty check to first place. || is a short circuit operator and will not check the next values is the first element gives true. If it is checked after, say isnan, it will give an error.

Upvotes: 1

Related Questions