
Looping through array to assign values to titles
12 views (last 30 days)
Show older comments
Hello,
I want to create a plot that contains a plot of each value of U_det and want each line assigned to each value in the array 'lateral'.
Now I have 5 different plots with the whole array in the legend.
Any ideas how to accomplish this?
Thanks
for i = abs(1:20:size(Bz,1))
Yi = Bz(i,minK(1,1));
lateral_1 = abs(RZ(:,1:49:245));%100.*find_coordinate(R2,Z2,Bz,0,Bi); % 100*: from [m] to [cm]
lateral = fliplr(lateral_1);
M_tot_spions_z = langevinfunc2(n,Kb,T,Brex(i,minK(1,1)), f, Vc, Ms,N);
U_det_r = abs((Yi.*M_tot_spions_z)/100e-9); % Counts 100[nV] Induced voltage [V]
figure;
txt = ['X=', num2str(lateral)];
plot(T_comb,U_det_r, 'DisplayName', txt)
% title([' Detected signal @ depth distance = ', num2str(abs(depth)),' [cm]'])
xlabel('Time [s]')
ylabel('Counts 100[nV]')
hold on
plot(T_comb, Noise)
legend show
end

0 Comments
Answers (1)
Vedant
on 9 Apr 2025 at 4:46
Edited: Vedant
on 9 Apr 2025 at 4:47
To plot lines for each value in the‘lateral’array corresponding to each value of‘U_det’, you should execute a loop separately to plot the values of the‘lateral’array within the existing loop. The following modifications may help achieve the desired results:
Initialize the Plot:Place the following lines at the top of your loop to create a single figure and hold the plots:
figure;
hold on;
Replace the Plotting Section:Replace the existing plotting code:
figure;
txt = ['X=', num2str(lateral)];
plot(T_comb, U_det_r, 'DisplayName', txt)
% title([' Detected signal @ depth distance = ', num2str(abs(depth)),' [cm]'])
xlabel('Time [s]')
ylabel('Counts 100[nV]')
hold on
plot(T_comb, Noise)
legend show
With the following code to plot each value of‘lateral’:
for j = 1:length(lateral)
txt = ['X=', num2str(lateral(j))];
plot(T_comb, U_det_r(j,:), 'DisplayName', txt)
end
plot(T_comb, Noise, 'DisplayName', 'Noise')
Finalize the Plot:After the loop ends, add the following lines to label the axes and display the legend:
xlabel('Time [s]')
ylabel('Counts 100[nV]')
legend show
By making these modifications, you will achieve the desired results. Below is an image showing the output using some dummy data:

0 Comments
See Also
Categories
Find more on Legend 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!