How to do 'if cell array contains any of these numbers, copy the content from other array of the same row'?

29 views (last 30 days)
Hi all, I have an array with each cell containing a youtube link, followed by a white space, followed by numbers that represent what sport was done in the video - something like: https://youtubelink.com 49, 56, 72. I have split the numbers from the youtube link and created a separate array that contains only the numbers of each youtube link. To simplify it, I use single digit numbers in this example and it looks something like this:
1 2
5 6 8 9
3 6 7 8
1 3 9
In this example, the relevant numbers I am looking for are 1, 2 and 9
How do I say 'As long as the row has one of those three relevant numbers, copy the cell of the same row from another array' ?
So row 2 contains 9, which is one of the relevant numbers, then I want to copy the youtube link in row 2 from another array.
Would ismember or find be suitable in this situation? I am unsure if these two functions can only be used when the numbers I am checking are the exact same as the relevant numbers, instead of just having one of the relevant numbers.
Thank you so much for your help in advance! Any suggestions or advice is appreciated.

Accepted Answer

Cris LaPierre
Cris LaPierre on 26 Nov 2024 at 21:26
Here's one way using any and ismember via cellfun
sport = {[1 2];
[5 6 8 9];
[3 6 7 8];
[1 3 9]};
link = ["link1";
"link2";
"link3";
"link4"];
nums = [1,2,9];
fxn = @(x) any(ismember(nums,x));
idx = cellfun(fxn,sport)
idx = 4x1 logical array
1 1 0 1
cpy = link(idx)
cpy = 3x1 string array
"link1" "link2" "link4"
  4 Comments
Cris LaPierre
Cris LaPierre on 27 Nov 2024 at 14:41
cellfun applies a function to each cell of a cell array individually. It's like running the function just on the contents of that one cell. Because this approach requires combining a couple functions, I used an anonymous function to create the function I need to run on each cell.
cellfun passes the cell contents as input to the function I designated. The anonymous function let's me assign this input to a variable named x, which is then used in my function calls. For more, see the link Walter shared.

Sign in to comment.

More Answers (0)

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!