Using logicals in arrayfun

조회 수: 2 (최근 30일)
Rashi Monga
Rashi Monga 2024년 7월 6일
댓글: Walter Roberson 2024년 7월 6일
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

채택된 답변

Walter Roberson
Walter Roberson 2024년 7월 6일
편집: Walter Roberson 2024년 7월 6일
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
Paul
Paul 2024년 7월 6일
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 2024년 7월 6일
Fixed the missing ) thanks!

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

추가 답변 (1개)

Paul
Paul 2024년 7월 6일
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
Rashi Monga
Rashi Monga 2024년 7월 6일
thank you for your response! this was helpful. :)

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

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by