How to save the output value from struct H(Index).b to variable f ?
Show older comments
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 Comments
Hi Aberna,
I understand that you are trying to iterate through ‘H’ and store each element’s ‘b’ field’s value into the variable ‘f’.
Here is a sample script which you can refer to:
Index = 1;
while Index<=3
%Column vector f is created in which "Index"
%holds the corresponding iteration's value of field b
% if condition
f(Index,1) = H(Index).b;
fprintf("Embedding Region %d\n",f(Index,1));
% end
Index = Index+1;
end
Please refer the following documentation for better understanding:
Aberna P
on 25 Sep 2023
Dyuman Joshi
on 26 Sep 2023
@Aberna P Could you please attach the whole code you are working with?
Answers (1)
akshatsood
on 13 Oct 2023
Edited: akshatsood
on 13 Oct 2023
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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!