Multiply structure by a constant

11 ビュー (過去 30 日間)
rockstar49
rockstar49 2023 年 1 月 12 日
コメント済み: Bora Eryilmaz 2023 年 1 月 12 日
Like to multiply a structure with fields by a constant, but it giving an error. Is there another way to do this?

回答 (2 件)

Matt J
Matt J 2023 年 1 月 12 日
編集済み: Matt J 2023 年 1 月 12 日
s.a=1; s.b=2,
s = struct with fields:
a: 1 b: 2
S=structfun(@(f)10*f,s,'uni',0) %multiply by 10
S = struct with fields:
a: 10 b: 20

Bora Eryilmaz
Bora Eryilmaz 2023 年 1 月 12 日
You have to cycle through the individual fields of the structure:
s = struct('a', [1 2 3 4], 'b', -1)
s = struct with fields:
a: [1 2 3 4] b: -1
for f = fieldnames(s)'
s.(f{1}) = 4 * s.(f{1});
end
s
s = struct with fields:
a: [4 8 12 16] b: -4
  2 件のコメント
rockstar49
rockstar49 2023 年 1 月 12 日
It is mainly 1 by 1 value, do you still need to do this as i have variable names
Bora Eryilmaz
Bora Eryilmaz 2023 年 1 月 12 日
Not sure what you mean by "variable names". Are you referring to the variable name of the struct or the fields of the struct?

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

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by