Using logicals in arrayfun
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Rashi Monga
am 6 Jul. 2024
Kommentiert: Walter Roberson
am 6 Jul. 2024
Hi,
I have two arrays:
tempA, size(10, 18)
tempB, size(1, 10) (is a column vector),
For each row in tempA, I want to extract the number of columns specified for that row by tempB. However, there are certain rows in tempB that are 'nan'.
u = arrayfun(@(x,y) x{1}(1:y), tempA, tempB, 'UniformOutput', false);
Can I use logical in the arrayfun so that it automatically excludes cases that are 'nan'?
Thank you
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 6 Jul. 2024
Bearbeitet: Walter Roberson
am 6 Jul. 2024
u = arrayfun(@(x,y) x{1}(1:max(0,y)), tempA, tempB, 'UniformOutput', false);
The secret here is that max(0,VALUE) is 0 if VALUE is nan. 1:0 is then empty, and indexing by empty is well-defined as being empty.
3 Kommentare
Paul
am 6 Jul. 2024
Missing a parenthesis after (0,y), but, that aside, u will contain cell elements that are empty arrays, if that's o.k. I thought those cases are to be excluded from the result.
Weitere Antworten (1)
Paul
am 6 Jul. 2024
rng(100)
tempA = rand(10,18);
tempB = 1:10;
u = arrayfun(@(x,y) x{1}(1:y), num2cell(tempA,2), tempB.', 'UniformOutput', false)
If all the odd numbered indices of tempB are nan:
tempB(1:2:end) = NaN;
u = arrayfun(@(x,y) x{1}(1:y), num2cell(tempA(~isnan(tempB),:),2), tempB(~isnan(tempB)).', 'UniformOutput', false)
Siehe auch
Kategorien
Mehr zu Linear Algebra finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!