Issues with code folding not following expected Rules

44 visualizaciones (últimos 30 días)
I am having an issue where the code folding doesn't seem to be following the normal protocols I expected it to. I expect the code folding to condense functions, for/while loops, and multi-lined comments. But I am seeing cases where the folding is happening from seemingly arbitrary lines.
For reference, I believe this code was originally written earlier this year on MATLAB R2021b but I have upgraded to R2023a in the past few weeks. I didn't notice the code folding issue until just now but I am unsure how long it's been present.
I apologize in advance for the large sections of code but from what I have seen elsewhere, code folding issues are often hard to replicate so I am keeping my original syntax in the code snippets.
Example 1:
Original Code: Lines 258 - 284
% Copy for running mat save file
% AutoSaveResultsByRun(matname,tInfo,vInfo,vals,runs,RunLogs,"OnlyUnchecked",true)
%% Find additional offset to get Kulites to rise at t=0
% This is important so that eventually the spectra calculations can be
% performed on a trace that is as 50/50 balanced as possible. For now,
% assume that the PCB references are aligned enough with the Kulites and
% that the relative delay is constant between the two sets. Therefore, we
% only need to institute the delay discovered by the reference Kulite
[~,itemp1] = min(abs(tshift(:,:,2)+0.1));
[~,itemp2] = min(abs(tshift(:,:,2)-0.1));
% Loop through each Reference Trace to detect the initial shock
iKulRef0 = zeros(R,1); % Indices needed to shift Kulite Data
for i = 1:R
[iKulRef0(i),res] = findchangepts(dat.Ch2(itemp1(i):itemp2(i),i),...
'Statistic','std');
end
% Generate the new time trace for the Kulite
tKul0 = tshift(:,:,1:2); % This only needs to have vectors for Ch1 and Ch2
% Find the time shift needed for each run. This should be highly constant
for i = 1:R
tKul0(:,i,:) = tKul0(:,i,:)-tshift(itemp1(i)+iKulRef0(i)-1,i,2);
end
% Save the full indices of these tKul0 locations
iKulRef0 = itemp1.' + iKulRef0 - 1;
Folded Code: Folds such that Lines 259 and 279 are adjacent and I have the following code visible
% Copy for running mat save file
% AutoSaveResultsByRun(matname,tInfo,vInfo,vals,runs,RunLogs,"OnlyUnchecked",true)
% Find the time shift needed for each run. This should be highly constant
for i = 1:R
tKul0(:,i,:) = tKul0(:,i,:)-tshift(itemp1(i)+iKulRef0(i)-1,i,2);
end
% Save the full indices of these tKul0 locations
iKulRef0 = itemp1.' + iKulRef0 - 1;
This code folding goes across a section break and includes both comments and code which makes no sense to me. Also this code folding option doesn't dissappear when I uncomment line 258 which invokes a separate function (in an external script) called AutoSaveResultsByRun. There don't appear to be any code folding issues in that separate function either.
Example 2:
Original Code: within local function part of same script - Lines 460 to 520. The confusion gets way worse as the folding and unfolding in this section is direction dependent because of internal code folds somehow.
function ...
...
...
% Populate the Channel Vectors --------------------------------------------
for i = R:-1:1 % Loop through each run (Backwards to avoid preallocation)
for j = 1:4 % Loop through each Channel
% Based on the Channel, Set reference data
if j <= 2; temp = kPa.(['Ch',num2str(j)]); % Kul Ref Matrices
else; temp = dat.(['Ch',num2str(j)]); % PCB Ref Matrices
end
% Now extract the data and insert into the appropriate substruct
y = temp(ia(j,i):ib(j,i),i);
d4spec.(['Ch',num2str(j)])(:,i) = y;
end
end
% Print that this has been complete
disp('Truncated Data-for-Spectra Calcs has been created')
end % End of function 1
% ======== Find Expansion Wave arrival ====================================
% This should be the end of the upper-step when the expansion waves impinge
% on the sensor array. At this time, a linear decay should begin
% -------------------------------------------------------------------------
% INPUTS:
% ia: The time index for the lower bounds of the search area
% ib: the time index for the upper bounds of the search area
% d: Data structure that has the time and Channels (d4spec)
% plotExpWaveID: Decide whether to plot these or not
% OUTPUTS:
% event: Index representing the expansion wave impingement (both Kul)
% -------------------------------------------------------------------------
function event = findExpWaveArrival(ia,ib,d,plotExpWaveID)
global Cruns; global SavePNG; % Call Global values
R = size(d.t,2); % Find the number of runs
event = zeros(R,2); % Preallocate the event matrix
% First find the event in channel 2 (Reference Kulite) --------------------
for i = 1:R
% Save temporary vector for now
temp = d.Ch2(ia(i):ib(i),i);
% Find the actual indices of the change point, use linear change
[ipt,~] = findchangepts(temp,'Statistic','linear');
event(i,2) = ia(i)+ipt-1; % Save that index value
% Create a temporary legend
templeg = {sprintf('Run %d: Ref Kul',Cruns.Run_num(i)),...
'Linear Fits',sprintf('t = %.3f ms',d.t(event(i,2),i))};
% Generate temporary FileName
figname = sprintf('Run%d-Ch2-Detect-ExpWaveArrival',Cruns.Run_num(i));
tempdir = fullfile('Figures','EventDetection',...
'ExpansionWaveArrival','RefKul');
figname = fullfile(tempdir,figname);
% Generate a plot too if desired
if plotExpWaveID
% Plot for visual confirmation
figure('Position',[124,287,764,360]);
findchangepts(temp,'Statistic','linear')
legend(sprintf('Run $d',Cruns.Run_num(i))); %#ok<CTPCT>
% Add some labels
ylabel('Pressure (kPa)');
legend(templeg,'Location','best','FontSize',12);
xlim([0 length(temp)])
set(gca,'FontSize',12)
% Save the figure if desired
if SavePNG; saveas(gcf,figname,'png'); end
end
end
...
...
...
end
Folded Code: Somehow this fold goes from an if statement, across a large comment block and into the middle of the next local function. I have no idea why this is happening.
function ...
...
...
% Populate the Channel Vectors --------------------------------------------
for i = R:-1:1 % Loop through each run (Backwards to avoid preallocation)
for j = 1:4 % Loop through each Channel
% Based on the Channel, Set reference data
if j <= 2; temp = kPa.(['Ch',num2str(j)]); % Kul Ref Matrices
tempdir = fullfile('Figures','EventDetection',...
'ExpansionWaveArrival','RefKul');
figname = fullfile(tempdir,figname);
% Generate a plot too if desired
if plotExpWaveID
% Plot for visual confirmation
figure('Position',[124,287,764,360]);
findchangepts(temp,'Statistic','linear')
legend(sprintf('Run $d',Cruns.Run_num(i))); %#ok<CTPCT>
% Add some labels
ylabel('Pressure (kPa)');
legend(templeg,'Location','best','FontSize',12);
xlim([0 length(temp)])
set(gca,'FontSize',12)
% Save the figure if desired
if SavePNG; saveas(gcf,figname,'png'); end
end
end
...
...
...
end
As of now, I haven't seen this behavior in any of my other scripts, but I haven't scoured through them all at this point. Also I hope the lack of context on the code's purpose doesn't hinder the clarity of my question.

Respuesta aceptada

Emma Farnan
Emma Farnan el 27 de Abr. de 2023
I actually just solved the issue by copy+pasting the entire code into a new script. I changed nothing, but the folding issues were no longer present.
Nonetheless, I am going to leave this question as "unanswered" for the moment so that it can be properly flagged as a potential issue when upgrading to R2023a - where I pressume the issue originated from.
  1 comentario
João GONÇALVES de Oliveira chueire
João GONÇALVES de Oliveira chueire el 24 de Mayo de 2023
Had the same problem and copy+pasting also worked for me
Copied into another file and then back in the original one and it worked fine.

Iniciar sesión para comentar.

Más respuestas (1)

alexander Mcghee
alexander Mcghee el 27 de Abr. de 2023
So you want MATLAB to be a great IDE, so do I...
try visual studio code
Integrate matlab with
and you can use co-pilot from github to help you code more effeciently. Its worth the rabbit hole

Categorías

Más información sobre Array Geometries and Analysis en Help Center y File Exchange.

Productos


Versión

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by