How to return result as NA rather than invalid line

조회 수: 1 (최근 30일)
Ismat Mohd Sulaiman
Ismat Mohd Sulaiman 2021년 7월 26일
댓글: Dave 2021년 7월 27일
Given the simple data below, I want to extract the result from the previous rows (L1 = rows-1, and L2 = rows-2). But L2 does not exist and MATLAB return as invalid and will not proceed. How to I return L2 = NA and allow the script to proceed?
data = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
[nrows, ncols] = size(data) %determine the number of rows and columns
for rows = 1:nrows %start with row 1 to nrows (number of rows in the table)
if data(rows,2) == 5 %and if that rows is equal to what we want
disp("Row " + rows + " has number 5")
L1 = data(rows-1, 2)
L2 = data(rows-2, 2)
% The L2 row doesn't exist. Running this will return invalid. How to show L2 = NA and not be invalid
else
disp("Row " + rows + " has no number 5")
end
end

답변 (1개)

Dave B
Dave B 2021년 7월 26일
How about something like this?
if rows-2 > 0 && rows-2 <= nrows
L2 = data(rows-2, 2);
else
L2 = nan;
end
  댓글 수: 2
Ismat Mohd Sulaiman
Ismat Mohd Sulaiman 2021년 7월 27일
Yup. Thanks. After I posted, I simply added another if else to the script, and it worked. 😊
Now I am thinking how to store all the results for L1 and L2 in an array 😁
Dave
Dave 2021년 7월 27일
Not sure where you're headed with the result, but there are a lot of solutions here that would skip the for loop altogether:
%% Alternative 1
ind = data(:,2) == 5; % Logical index of second column == 5
hit = find(ind); % Row number where second column == 5
L1 = nan(sum(ind),1); % Initialize L1 to have an item for each hit
L2 = nan(sum(ind),1); % Initialize L2 to have an item for each hit
L1(hit>1) = data(hit(hit>1)-1, 2); % L1, where the hit row is bigger than one, should get the previous row, second column
L2(hit>2) = data(hit(hit>2)-2, 2); % L2, where the hit row is bigger than two, should get two rows up, second column
% display the rows that don't have a 5:
miss = find(~ind);
disp(compose("Row %d has no number 5 (in the second column)", miss))
%% Alternative 2
L1 = [nan; data(:,2)]; % Pad the second column of data with a NaN
L2 = [nan; nan; data(:,2)]; % Pad the second column of data with two NaNs
ind = data(:,2) == 5; % true where data's second column is a 5
L1 = L1(ind); % Now just keep the items that were relevant
L2 = L2(ind);
% disp for the misses is the same as above
% * your code checked whether the second column had aa 5, if you wanted to
% check if *any* item in the row is a 5, try any(data==5, 2) for ind

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by