Effacer les filtres
Effacer les filtres

multiply each element of structured array, assignment of structured array

42 vues (au cours des 30 derniers jours)
John Petersen
John Petersen le 11 Mar 2013
Commenté : Ella le 7 Juin 2023
I'm not exactly sure if I'm using the right terminology. I have
A(1).B = 5;
A(2).B = 6;
A(3).B = 7;
>>A.B
ans =
5
ans =
6
ans =
7
I have two questions: 1. I want to multiply each element of the structured array so that A.B*2 would equal 10,12,14 instead of 5,6,7. but instead I get the error
>>A.B*2
Error using *
Too many input arguments.
2. How do I make a copy of the structured array? I have tried but it just results in the first element.
>>C = A.B
C =
5
Likewise
>> C = A(1:3).B
C =
5
instead of C(1).B = 5, C(2).B = 6, and C(3).B = 7 like I want.

Réponse acceptée

per isakson
per isakson le 11 Mar 2013
Modifié(e) : per isakson le 11 Mar 2013
The short answer is NO, it is not possible. However, ...
>> [A.B] = split( 2*[A.B] )
A =
1x3 struct array with fields:
B
>> A.B
ans =
10
ans =
12
ans =
14
where
function varargout = split( vec )
assert( nargout == numel( vec ) ...
, 'split:narginNargoutMismatch' ...
, 'The number of outputs should match the length of the input vector.')
varargout = num2cell( vec );
end

Plus de réponses (1)

Jan
Jan le 11 Mar 2013
Modifié(e) : Jan le 11 Mar 2013
C = [A(1:3).B];
% or C = [A(:).B]
% or C = [A.B]
This replies [5,6,7]. To get C(1).B = 5, C(2).B = 6, C(3).B = 7:
C = A;
A direct multiplication is not possible. Structs are simply not designed for arithmetic operations, because this can be done with numerical arrays much better. But it is possible with a loop:
F = fieldnames(A);
for iF = 1:length(F)
aF = F{iF};
A.(aF) = A.(aF) * 2;
end
  2 commentaires
John Petersen
John Petersen le 11 Mar 2013
In this case C is converted to an array. I want to be able to keep it a structured array.
I only want A.B to be copied and there are other fields associated with A that I don't want copied to C. thanks.
Ella
Ella le 7 Juin 2023
Hi! So I have a structure with a variable amount of entries. It will always be greater than 1. These stats (Area, MinFeret.. etc) need to be converted to mm. I tried to use the for loop approach, but it says there are too many inputs. Here is my code.
F= fieldnames(stats);
for iF = 1:length(F)
aF = F{iF};
stats.(aF) = stats.(aF) .* pixelSize;
end
Any advice for how I can make it work or another way to do this?

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by