How to optimize IF statement with Multiple Conditions.
10 次查看(过去 30 天)
显示 更早的评论
Sai Gudlur
2024-9-25
Hello,
I have five Tables (T1 to T5) and Conditons CR ranging from ( 0-4) . When I process a files each file may have one condition in it or multiple conditons. For example ( it could have Condition 3 or in the next file it could be 0,2 & 4). Which ever condtiion is satisfied that particular table (if one condition) and (Multiple table Verticat into one final table).
I tried using multiple methods like
1) If any or all statments didn't work.
2) if I have to use ismember then I could have make multiple array of condition hard coded into the script. Example: Condition:if ismember([1 2], CR]'
Final_Table = verticat(T2;T3).
Could someone suggest a robust and quicker way.
If possible provide with a Script sketon or example so It could be understood better and also your time and effort is well respected.
Thank you
8 个评论
dpb
2024-9-25
编辑:dpb
2024-9-25
As per usual, you'll have a let better luck in getting useful responses if you will attach representative data files so that people here can actually see what you have that you're trying to describe. Then illustrate for those files what the expected result would be.
One note is that if by "I have five Tables (T1 to T5) " you mean you have created five MATLAB variables T1 through T5 and are trying to operate on them programmatically making logic decisions based on the variable name or even just processing them in a similar fashion, creating sequentially-numbered variables in this fashion is almost never the right way to go...instead, use an array of tables or merge what is/are the unique variable/(s) into the one overall table as additional variables with the distinguishing value(s). Then you can operate by those characteristic values without having to duplicate code with various combinations of hardcoded variables as you are illustrating above.
But, rather than us trying to guess; provide the example data files and it's likely there will be pretty painless ways to do what you're atttempting.
ADDENDUM:
But, if the issue were to boil down to a case of an if construct with multiple conditions, the most likely way to simplify it would be with a switch, case, otherwise construct rather than an if, elseif, else. But, given the description, I don't think your problems revolve around that choice but in how you're handling the data files initially.
Sai Gudlur
2024-9-26
Hello dpb,
True it might be better to share my script rather than posing a question with vague example. Have added my script below.
My Cases are changing based on the Values of a variable Active_Slot_Ids. So when you look at cases I do not have a combination of all the possibilities of combination that could be in Active_Slot_Ids ranging [0-4]. I would be uploading numerous files and each file has its own combination of Active_Slot_Ids.
I am sure I am missing a trick when in I could Check what are the numbers are present in Active_Slot_Ids and then based of that verticat my complete table.
Please do let me know if you can think of a solution. Thank you for your suggestion and Time.
Thanks
Sai
[filelist,pathn] = uigetfile('*.txt','Please Select a Par Files', 'multiselect', 'on');
if isnumeric(filelist);
error('no file selected');
end
filelist = cellstr(filelist);
filelist = fullfile(pathn, filelist);
N = numel(filelist);
Cal_Rev = cell(1,N);
% pre-allocate Cal_Rev
tic
for K = 1:N
filename = filelist{K};
File_Details = importdata(filename);
Cal_Rev(K) = extract(File_Details.textdata{1,1},digitsPattern(5,9));
extracted_variant = extract(filename, digitsPattern(3,9));
if isempty(extracted_variant)
error('No valid variant number found in filename');
else
Variant_Number{K} = extracted_variant{1}; % Assign first match to the cell array
end
%Variant_Number(K) = extract(filename,digitsPattern(3,9));
Variant_Name(K) = extractBetween(File_Details.textdata{6,1},"_dev_","Spd_");
% extract digits after the underscore at the end of textdata{1}:
Version = regexp(File_Details.textdata{1},'_(\d+)$','tokens','once');
Version = 1+str2double(Version{1});
Data_in = readtable(filename, 'Delimiter',{',',';',' '});
Par_File_Parameters = Data_in.Var1(:);
Parameter_List = importdata('C:\Users\C3065290\Documents\GPP Practice\Parameter List.txt');
GPP_Names = importdata('C:\Users\C3065290\Documents\GPP Practice\GPP_NAME.txt');
Slot_PG_List = importdata('C:\Users\C3065290\Documents\GPP Practice\Slot_Id.txt');
Slot_Compare = contains(Par_File_Parameters,Slot_PG_List);
Slot_Data = Data_in(Slot_Compare,:);
Slot_Data_Value_Compare = lt(Slot_Data.Var4,255);
Slots_Active = Slot_Data.Var1(Slot_Data_Value_Compare);
Final_Names = table(Parameter_List,GPP_Names);
[C,ia,ib] = intersect(Par_File_Parameters,Parameter_List,"stable");
Common_Data = Data_in(ia,:);
Common_Data_1 = horzcat(Common_Data,Final_Names);
[~,idx] = ismember(Common_Data_1.Var1,Common_Data_1.Parameter_List);
Common_Data_1(:,["Parameter_List","GPP_Names"]) = Common_Data_1(idx,["Parameter_List","GPP_Names"]);
TF_Economy = endsWith(Common_Data_1.Var1,'_00');
TF_Standard = endsWith(Common_Data_1.Var1,'_01');
TF_Performance = endsWith(Common_Data_1.Var1,'_02');
TF_Tanker = endsWith(Common_Data_1.Var1,'_03');
TF_Off_Road = endsWith(Common_Data_1.Var1,'_04');
Active_Slot_Ids = str2double(extractAfter(Slots_Active,'C_PG_SlotPGID_'));
TF_Eco_Table = Common_Data_1(TF_Economy,["GPP_Names","Parameter_List","Var8"]);
TF_Standard_Table = Common_Data_1(TF_Standard,["GPP_Names","Parameter_List","Var8"]);
TF_Performance_Table = Common_Data_1(TF_Performance,["GPP_Names","Parameter_List","Var8"]);
TF_Tanker_Table = Common_Data_1(TF_Tanker,["GPP_Names","Parameter_List","Var8"]);
TF_Off_Road_Table = Common_Data_1(TF_Off_Road,["GPP_Names","Parameter_List","Var8"]);
Complete_Table;
switch(Complete_Table)
case [0 1 2 3 4]
Complete_Table{K} = vertcat(TF_Eco_Table,TF_Standard_Table,TF_Performance_Table,TF_Tanker_Table,TF_Off_Road_Table);
case [1 2 3 4]
Complete_Table{K} = vertcat(TF_Standard_Table,TF_Performance_Table,TF_Tanker_Table,TF_Off_Road_Table);
case [2 3 4]
Complete_Table{K} = vertcat(TF_Performance_Table,TF_Tanker_Table,TF_Off_Road_Table);
case [3 4]
Complete_Table{K} = vertcat(TF_Tanker_Table,TF_Off_Road_Table);
otherwise
Complete_Table{K} = vertcat(TF_Tanker_Table,TF_Off_Road_Table);
end
make unique column names (names in all tables must be distinct before concatenating):
N = size(Complete_Table{K},2);
Complete_Table{K}.Properties.VariableNames = sprintf("Var%d_",K) + compose("%d",1:N);
% add two new rows at the top:
new_rows = { ...
sprintf('SW Label: %s',Cal_Rev{K}),sprintf('Variant Name: %s',Variant_Name{K}), NaN; ...
sprintf('Cal_Revision: %d',Version),sprintf('Variant Number: %s',Variant_Number{K}), NaN; ...
};
Complete_Table{K} = [new_rows; Complete_Table{K}];
end
toc
New_Table = [Complete_Table{:}];
[Output_Filename,Output_Pathname] = uiputfile("*.xlsx");
Output_File = fullfile(Output_Pathname,Output_Filename);
writetable(New_Table,Output_File);
Sai Gudlur
2024-9-26
Hello dpb,
The switch commands won't work and I tried the Crude way of using For loops with verfying the Active_Slot_Ids Vector. Problem is it was only veryfing the last FOR loop and not Checking all the FOR Loops before it.
1) Tried inline FORLOOPS where FOR & END are inline
2) Also indentend (NOT NESTED i know) just indent but this did not serve the purpose either.
Could you offer a suggestion or help?
Thanks
Sai
[filelist,pathn] = uigetfile('*.txt','Please Select a Par Files', 'multiselect', 'on');
if isnumeric(filelist);
error('no file selected');
end
filelist = cellstr(filelist);
filelist = fullfile(pathn, filelist);
N = numel(filelist);
Cal_Rev = cell(1,N);
% pre-allocate Cal_Rev
tic
for K = 1:N
filename = filelist{K};
File_Details = importdata(filename);
Cal_Rev(K) = extract(File_Details.textdata{1,1},digitsPattern(5,9));
extracted_variant = extract(filename, digitsPattern(3,9));
if isempty(extracted_variant)
error('No valid variant number found in filename');
else
Variant_Number{K} = extracted_variant{1}; % Assign first match to the cell array
end
%Variant_Number(K) = extract(filename,digitsPattern(3,9));
Variant_Name(K) = extractBetween(File_Details.textdata{6,1},"_dev_","Spd_");
% extract digits after the underscore at the end of textdata{1}:
Version = regexp(File_Details.textdata{1},'_(\d+)$','tokens','once');
Version = 1+str2double(Version{1});
Data_in = readtable(filename, 'Delimiter',{',',';',' '});
Par_File_Parameters = Data_in.Var1(:);
Parameter_List = importdata('C:\Users\C3065290\Documents\GPP Practice\Parameter List.txt');
GPP_Names = importdata('C:\Users\C3065290\Documents\GPP Practice\GPP_NAME.txt');
Slot_PG_List = importdata('C:\Users\C3065290\Documents\GPP Practice\Slot_Id.txt');
Slot_Compare = contains(Par_File_Parameters,Slot_PG_List);
Slot_Data = Data_in(Slot_Compare,:);
Slot_Data_Value_Compare = lt(Slot_Data.Var4,255);
Slots_Active = Slot_Data.Var1(Slot_Data_Value_Compare);
Final_Names = table(Parameter_List,GPP_Names);
[C,ia,ib] = intersect(Par_File_Parameters,Parameter_List,"stable");
Common_Data = Data_in(ia,:);
Common_Data_1 = horzcat(Common_Data,Final_Names);
[~,idx] = ismember(Common_Data_1.Var1,Common_Data_1.Parameter_List);
Common_Data_1(:,["Parameter_List","GPP_Names"]) = Common_Data_1(idx,["Parameter_List","GPP_Names"]);
TF_Economy = endsWith(Common_Data_1.Var1,'_00');
TF_Standard = endsWith(Common_Data_1.Var1,'_01');
TF_Performance = endsWith(Common_Data_1.Var1,'_02');
TF_Tanker = endsWith(Common_Data_1.Var1,'_03');
TF_Off_Road = endsWith(Common_Data_1.Var1,'_04');
Active_Slot_Ids = str2double(extractAfter(Slots_Active,'C_PG_SlotPGID_'));
TF_Eco_Table = Common_Data_1(TF_Economy,["GPP_Names","Parameter_List","Var8"]);
TF_Standard_Table = Common_Data_1(TF_Standard,["GPP_Names","Parameter_List","Var8"]);
TF_Performance_Table = Common_Data_1(TF_Performance,["GPP_Names","Parameter_List","Var8"]);
TF_Tanker_Table = Common_Data_1(TF_Tanker,["GPP_Names","Parameter_List","Var8"]);
TF_Off_Road_Table = Common_Data_1(TF_Off_Road,["GPP_Names","Parameter_List","Var8"]);
for Active_Slot_Ids= [0,1,2,3,4]'
Complete_Table{K} = vertcat(TF_Eco_Table,TF_Standard_Table,TF_Performance_Table,TF_Tanker_Table,TF_Off_Road_Table);
for Active_Slot_Ids= [1,2,3,4]'
Complete_Table{K} = vertcat(TF_Standard_Table,TF_Performance_Table,TF_Tanker_Table,TF_Off_Road_Table);
for Active_Slot_Ids= [0,2,3]'
Complete_Table{K} = vertcat(TF_Eco_Table,TF_Performance_Table,TF_Tanker_Table);
for Active_Slot_Ids= [1]'
Complete_Table{K} = vertcat(TF_Standard_Table);
for Active_Slot_Ids= [1,3]'
Complete_Table{K} = vertcat(TF_Standard_Table,TF_Tanker_Table);
end
end
end
end
end
Stephen23
2024-9-26
编辑:Stephen23
2024-9-26
Note that FOR actually iterates over the columns of the provided array:
So your code with its (convoluted indirectly defined) column vectors will iterate exactly once for each FOR loop:
for Active_Slot_Ids= [0,1,2,3,4]'
disp('before')
disp(Active_Slot_Ids)
disp('after')
end
before
0
1
2
3
4
after
That is not five separate iterations, that is exactly one iteration. Which means that none of your loops do anything useful, they are entirely superfluous.
If you want multiple iterations (with a scalar each time) then supply a row vector:
for Active_Slot_Ids = 0:4
disp('before')
disp(Active_Slot_Ids)
disp('after')
end
before
0
after
before
1
after
before
2
after
before
3
after
before
4
after
Yes, this "feature" makes no sense. Yes, it causes more bugs than it has ever been useful. Yes, TMW should get rid of it.
Sai Gudlur
2024-9-26
Hello Stephen,
Thanks for your time but I cannot have FOR loop in Range of 0:4 as sometimes Active_Slots_Ids may not have numbers in sequence. For Example in the Script I have the 3rd FOR Loop as below. And each Active Slot_id signifies certain table and only the the digit present need to be put together in Complete_Table.
for Active_Slot_Ids= [0,2,3]'
Complete_Table{K} = vertcat(TF_Eco_Table,TF_Performance_Table,TF_Tanker_Table);
Stephen23
2024-9-26
编辑:Stephen23
2024-9-26
"Thanks for your time but I cannot have FOR loop in Range of 0:4 as sometimes Active_Slots_Ids may not have numbers in sequence. For Example in the Script I have the 3rd FOR Loop as below. And each Active Slot_id signifies certain table and only the the digit present need to be put together in Complete_Table."
Nothing in my comment is about the values your loop uses. Use whatever values you want.
My comment explains why the orientation of your vectors is very unlikely to do what you want. And in the unlikely case that you do want that behavior, then your FOR loops are entirely superfluous. Which seems unlikely to me.
In any case, the values you are using has nothing to do with my comment:
for Active_Slot_Ids = [0,2,3]' % this will not work. The values are not the reason.
Sai Gudlur
2024-9-26
Thanks Stephen I used a little different Approach by using ismember and comparing them to Active Slots and runniung through multiple if and elseif and it worked. Little labourious but does the job.
Thanks You
dpb
2024-9-26
I would venture there are ways to reduce the tedium, but you forgot to attach sample data files for anybody to be able to look at to see how to make more efficient...
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!发生错误
由于页面发生更改,无法完成操作。请重新加载页面以查看其更新后的状态。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
亚太
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)