フィルターのクリア

How do I extract all rows of a struct field that is a character array?

62 ビュー (過去 30 日間)
Pat Canny
Pat Canny 2019 年 12 月 6 日
コメント済み: Gordon Lai 2021 年 3 月 5 日
I want to extract all rows of a field within a struct. The field is a character array.
For sake of example, the struct is called systemData, with a field called Objects, which has a field called status (among many others). The status field is a char, and has 20 rows.
I'd like to extract all 20 rows of systemData.systemObjects.status
When I try "normal" index operations, I either only get one result, or I get an error.
Here is one attempt, which results in an error:
systemData.Objects.status{:}
Error: Expected one output from a curly brace or dot indexing expression, but there were 20 results.
I also tried this:
test_extract = systemData.Objects.status;
But I only get the first row.
How do I extract all rows?

採用された回答

Pat Canny
Pat Canny 2019 年 12 月 6 日
First, try to avoid using character arrays. Convert them to string arrays.
Second, you need to use the {curly brace syntax} to extract multiple elements.
Try this:
object_status = string({systemData.Objects.status})';
  3 件のコメント
Adam Sifounakis
Adam Sifounakis 2019 年 12 月 6 日
Strings are better than character arrays in (almost) every way.
  1. Strings are faster than cell arrays of character arrays (cellstr)
  2. You can vectorize operations, like concatenating the + (plus) operator
  3. Code written for strings is more easy to understand, use, and maintain
For example, creating a list of 1000 file names used to require a for loop and sprintf, but MATLAB's strings make this super easy!
filenames = "image_" + (1:1000)' + ".png"
Note: The only reason for the parentheses and apostrophe is because I wanted to make it a column vector. I like looking at my file names as a column.
We're going to take your feedback about making our recommendation more clear into consideration. Thanks for pointing this out!
In the meantime, you can find more information about strings on Loren's blog post:
and the Documentation page for updating your code to accept strings:
Gordon Lai
Gordon Lai 2021 年 3 月 5 日
Thanks, I have had this problem using the "dir" command...!
If strings are recommended, is there a reason for using char arrays as the default struct field for "dir"?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by