Effacer les filtres
Effacer les filtres

Using logicals in arrayfun

24 vues (au cours des 30 derniers jours)
Rashi Monga
Rashi Monga le 6 Juil 2024 à 20:47
Commenté : Walter Roberson le 6 Juil 2024 à 22:26
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

Réponse acceptée

Walter Roberson
Walter Roberson le 6 Juil 2024 à 21:14
Modifié(e) : Walter Roberson le 6 Juil 2024 à 22:26
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 commentaires
Paul
Paul le 6 Juil 2024 à 21:56
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.
Walter Roberson
Walter Roberson le 6 Juil 2024 à 22:26
Fixed the missing ) thanks!

Connectez-vous pour commenter.

Plus de réponses (1)

Paul
Paul le 6 Juil 2024 à 21:16
rng(100)
tempA = rand(10,18);
tempB = 1:10;
u = arrayfun(@(x,y) x{1}(1:y), num2cell(tempA,2), tempB.', 'UniformOutput', false)
u = 10x1 cell array
{[ 0.5434]} {[ 0.2784 0.2092]} {[ 0.4245 0.1853 0.8176]} {[ 0.8448 0.1084 0.3361 0.3819]} {[ 0.0047 0.2197 0.1754 0.0365 0.2100]} {[ 0.1216 0.9786 0.3728 0.8904 0.5447 0.3402]} {[ 0.6707 0.8117 0.0057 0.9809 0.7691 0.1781 0.6023]} {[ 0.8259 0.1719 0.2524 0.0599 0.2507 0.2377 0.3878 0.3404]} {[ 0.1367 0.8162 0.7957 0.8905 0.2859 0.0449 0.3632 0.0921 0.3131]} {[0.5751 0.2741 0.0153 0.5769 0.8524 0.5054 0.2043 0.4635 0.6340 0.6576]}
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)
u = 5x1 cell array
{[ 0.2784 0.2092]} {[ 0.8448 0.1084 0.3361 0.3819]} {[ 0.1216 0.9786 0.3728 0.8904 0.5447 0.3402]} {[ 0.8259 0.1719 0.2524 0.0599 0.2507 0.2377 0.3878 0.3404]} {[0.5751 0.2741 0.0153 0.5769 0.8524 0.5054 0.2043 0.4635 0.6340 0.6576]}
  1 commentaire
Rashi Monga
Rashi Monga le 6 Juil 2024 à 21:32
thank you for your response! this was helpful. :)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by