This question is closed. Reopen it to edit or answer.

MATLAB how to display negative values if any in code

1 view (last 30 days)
This code shows a section of a data sheet. How would I make it so if there is a negative value detected in the table NNeg, it would display the location and then
allow the user to correct it by imputting a replacement value until an positive number is entered.
load Saturated_Table
load SpecificHeat_Data
SAT = SaturatedTable;
SH = SpecificHeatData;
NNeg = SaturatedTable(1:end , 2:end);
if NNeg<0

Answers (1)

Harry Laing
Harry Laing on 10 Dec 2020
One way would be to use a for loop to go through each cell in the matrix and test to see if it is negative, and if so require an input as a replacement. It's not the fastest or most efficient, but it would work:
NNeg = SaturatedTable(1:end , 2:end);
[NumRows, NumCols] = size(SaturatedTable);
%The code below will move horizontaly across each data point in the matrix, and test < 0
for i = 1:NumRows % For every Row
for j = 1:NumCols % For every Column
if SaturatedTable(i,j)<0 % Perform test
disp(['Negative Data at point: (',num2str(i),' ',num2str(j),')']) %Display non-negative location
new_value = input('Please Provide a positive number replacement: ') % Ask for replacement
while new_value(i,j) < 0 % Check input is positive
new_value = input('Previous input error, please Provide a positive number replacement: ')
SaturatedTable(i,j) = new_value; % Update our table with new value
Note: This wouldnt prevent anyone from entering text instead of a number, so there's probably more checks needed after the input, but as a starter for 10 this should work.


Community Treasure Hunt

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

Start Hunting!

Translated by