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

27 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 26 Nov. 2024 um 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 Kommentare
Cris LaPierre
Cris LaPierre am 27 Nov. 2024 um 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by