How do I access an element in an answer array directly?
古いコメントを表示
I have a variable named snsr_type as defined below. I want extract just "Diff" and store it in snsr_type variable. I have to do this in 2 steps.
snsr_name = "Diff sensor A1";
snsr_type = split(snsr_name,' ');
snsr_type = snsr_type(1);
If I combine those last 2 lines like this, it errors out saying "Error: Invalid array indexing.". I've also tried wrapping the first part in () like (split(snsr_name,' '))(1). This also doesn't work.
snsr_type = split(snsr_name,' ')(1);
Is there any way of doing this simply in a single line? Or do I have to do this in 2 lines?
6 件のコメント
Stephen23
2025 年 4 月 24 日
"Is there any way of doing this simply in a single line?"
snsr_type = split(snsr_name,' '); snsr_type = snsr_type(1);
Kishore
2025 年 4 月 24 日
Image Analyst
2025 年 4 月 25 日
🤣
Paul Lambrechts
2025 年 4 月 25 日
How about:
snsr_type = extractBefore(snsr_name,' ');
snsr_name = "Diff sensor A1";
snsr_type = extractBefore(snsr_name,' ') % Get first word, which is the sensor type
Kishore
2025 年 4 月 28 日
採用された回答
その他の回答 (1 件)
Two approaches:
First = @(V) V(1);
snsr_name = "Diff sensor A1";
snsr_type1 = First(split(snsr_name,' '))
snsr_type2 = struct('Data', split(snsr_name,' ')).Data(1)
2 件のコメント
A third (somewhat complicated) way:
snsr_name = "Diff sensor A1";
y = subsref(split(snsr_name, ' '), substruct('()', {1}))
The simplest approach is likely to be faster in many situations:
timeit(@f0)
timeit(@f1)
timeit(@f2)
timeit(@f3)
function f0()
snsr_name = "Diff sensor A1";
snsr_type = split(snsr_name,' ');
snsr_type = snsr_type(1);
end
function f1()
First = @(V) V(1);
snsr_name = "Diff sensor A1";
snsr_type = First(split(snsr_name,' '));
end
function f2()
snsr_name = "Diff sensor A1";
snsr_type = struct('Data', split(snsr_name,' ')).Data(1);
end
function f3()
snsr_name = "Diff sensor A1";
snsr_type = subsref(split(snsr_name, ' '), substruct('()', {1}));
end
カテゴリ
ヘルプ センター および File Exchange で Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!