Reversing parts of (even) items in a listbox (cellarray)
2 次查看(过去 30 天)
显示 更早的评论
Hello, I have items in a listbox (so cell array) - the integers before the "r" can be any number from 1-12.
My aim is to take any line containing an even number after r (r2, r4 etc) and reverse the other numbers and then put back into the list box
So line 2 & 4 would change to
1 2 3 r2 -> 3 2 1 r2
1 2 3 r4 -> 3 2 1 r4
This was my attempt.
items=app.ListBoxPos.Items
nl=numel(items);
rstr=["r2","r4","r6","r8"];
s1=[];
out={};
for i=1:nl
line=char(items(i));
if contains(line, rstr)
tokens = strsplit(line, 'r' )
t=fliplr(tokens{1,1})
new=[t,' r',tokens{1,2}]
app.ListBoxPos.Items{i}=new
%Not sure what to do now!
end
end
Not sure if this is the most elegant way, and it falls over trying to overwrite the line in the listbox.
Thanks for any help
Jason
0 个评论
采纳的回答
Cris LaPierre
2021-1-18
You can use mod to determine if the last number is even or not. I would then use indexing to reverse the order of the rows that end in an even number.
items=app.ListBoxPos.Items
nl=numel(items);
for i=1:nl
if mod(items{i}(end),2)==0
out{i}=items{i}([end-3:-1:1 end-2:end]);
else
out(i)=items(i);
end
end
app.ListBoxPos.Items = out;
8 个评论
Cris LaPierre
2021-1-19
编辑:Cris LaPierre
2021-1-19
What version of MATLAB are you using?
It's good to see you coming up with your own approach. Nice job. Just be aware that this solution suffers from the original problem - it doesn't work when the final number has 2 digits (10 or 12).
更多回答(1 个)
Jason
2021-1-19
编辑:Jason
2021-1-19
1 个评论
Cris LaPierre
2021-1-19
When the number at the end is 2 characters, it would require a different approach. Perhaps finding the 'r' and using that to set the index rather the 'end'.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dialog Boxes 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!