How to save the output value from struct H(Index).b to variable f ?

1 次查看(过去 30 天)
Code:
Index=1;
if(H(Index).e > 0.5 && H(Index).c > 0.9 || H(Index).c < 0.5 && H(Index).en > 0.2 && (H(Index).x)>10)
f=H(Index).b;
fprintf("Embedding Region %d\n",f);
Index=Index+1;
Explain:
Actually the H struct has five field and based on the if condition it display the output correctly but the issue is, all the values is not stored in variable ' f ', only the last value is shown as f value? How to store all the selected values to the variable f? If i declare f as array then also the last value is alone store in f? where am lagging am not getting? Can anybody suggest solution.
Thanks in Adavnce.
  3 个评论
Aberna P
Aberna P 2023-9-25
Thanks for the response divyanshu. But it doesnt work, it print 1 as the output for nymber of n times. its not storing the b values in f.

请先登录,再进行评论。

回答(1 个)

akshatsood
akshatsood 2023-10-13
编辑:akshatsood 2023-10-13
Hi Aberna,
I understand that you want to store the output from a struct 'H' into a variable 'f'. To achieve this, you need to declare the variable 'f' as a vector with the same size as 'H'. Based on the provided code snippet and the information given in the question, I have assumed the existence of a struct 'H' and prepared a script to guide you through the correct approach. Please refer to the code snippet attached herewith.
% create an empty struct array
H = struct('e', [], 'c', [], 'en', [], 'x', [], 'b', []);
% generating random values for each field
for i = 1:5
H(i).e = round(0.5+rand(1), 1);
H(i).c = round(1+rand(1), 1);
H(i).en = round(rand(1), 1);
H(i).x = round(10*rand(1), 1);
H(i).b = round(rand(1), 1);
end
% preallocating f to store the output
f = zeros(1,5);
Index = 1;
while Index <= 5
if (H(Index).e > 0.5 && H(Index).c > 0.9) || ((H(Index).c < 0.5 && H(Index).en > 0.2) ...
&& (H(Index).x > 10))
f(Index) = H(Index).b;
fprintf("Embedding Region %.1f\n",f(Index));
end
Index=Index+1;
end
Now, the variable 'f' will store the value corresponding to the field 'b' in the struct 'H'. Since the complete code was not provided, I have made assumptions to illustrate the correct methodologies. Update the above code as per your needs.
I hope this helps.

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by