How to return result as NA rather than invalid line
3 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Dave B
on 26 Jul 2021
How about something like this?
if rows-2 > 0 && rows-2 <= nrows
L2 = data(rows-2, 2);
else
L2 = nan;
end
2 Comments
Dave
on 27 Jul 2021
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
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!