How to return result as NA rather than invalid line

4 次查看(过去 30 天)
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
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 中查找有关 Logical 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by