Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a vector of strings (or chars) when input data is an object with chars (not concatenated chars)

If I have a class like this:

classdef Person
  properties
    Name
    Age
    Weight
  end
  methods
    function obj = Person(name, age, weight)
      obj.Name = name;
      obj.Age = age;
      obj.Weight = weight;
    end
  end
end

And attempt to create a vector of just the names like this:

angus = Person("Angus Comber", 40, 73);
lisa  = Person("Lisa Comber", 39, 60);
jack  = Person("Jack Comber", 4, 15);
family = [angus lisa jack];

just_names = [family(:).Name];

Then the result is what I want:

>> just_names
just_names = 
  1×3 string array
    "Angus Comber"    "Lisa Comber"    "Jack Comber"

But if I create the Person's like this:

angus = Person('Angus Comber', 40, 73);
lisa  = Person('Lisa Comber', 39, 60);
jack  = Person('Jack Comber', 4, 15);
family = [angus lisa jack];

just_names = [family(:).Name];

Then I get:

>> just_names
just_names =
    'Angus ComberLisa ComberJack Comber'

Unfortunately, the input names in my sample are all chars (not strings). So given the char input, how can I edit the code to get the array I want?

like image 888
Angus Comber Avatar asked Dec 21 '25 13:12

Angus Comber


1 Answers

It may not be quite what you want because it doesn't result in a vector of strings but changing the final line of the code to

just_names = {family(:).Name};

with the curly braces, will give the result

just_names =

  1×3 cell array

    {'Angus Comber'}    {'Lisa Comber'}    {'Jack Comber'}

So it avoids appending the characters of the names together.

like image 83
Neil Butcher Avatar answered Dec 24 '25 03:12

Neil Butcher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!