Filter löschen
Filter löschen

Is there a command that can check if a string is present in a certain array and output that same string?

12 Ansichten (letzte 30 Tage)
Hi i want to make checks to some string array with variable dimension and i tried doing what's written in the code. I know the problem is the code in the "if" but i don't know what to do... All the functions i know that find a string in an array return an array of logical 0 and 1. I can transform the array in the same dimension by putting 0 in all the seasons that aren't present and add some || in the if statement but i feel it's less practical, and i simply want to know if it's possible.
%The first column is for other purposes
L = {1, ["Spring", "Summer"]; 0, ["Winter", "Summer","Autumn"]}
i=0;
while (i<2)
i = i+1;
if (L{i,2}(:)=="Winter")
fprintf("Yes")
end
end

Akzeptierte Antwort

Voss
Voss am 15 Feb. 2023
I'm confused about what you want the output to be.
L = {1, ["Spring", "Summer"]; 0, ["Winter", "Summer","Autumn"]};
ism = cellfun(@(x)ismember("Winter",x),L(:,2))
ism = 2×1 logical array
0 1
  7 Kommentare
Voss
Voss am 16 Feb. 2023
Exactly. It's the same as this:
C = {[1 2 3],[4 5 6 7],[8 9]};
f = @(x)x(1);
cellfun(f,C) % apply the function f to the contents of each cell of C
ans = 1×3
1 4 8
Walter Roberson
Walter Roberson am 16 Feb. 2023
ism = cellfun(@(x)ismember("Winter",x),L(:,2))
is the same as
InternalTemporaryVariable = @(x)ismember("Winter",x);
ism = cellfun(InternalTemporaryVariable, L(:,2));
clear InternalTemporaryVariable
That is, the temporary anonymous function is created before cellfun is called, and is removed after the call (because there are no more references to it.)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by