Loop "Replace String" from different string arrays
10 views (last 30 days)
Show older comments
Hi
I have different strings which replace as below:
First array:

Second array:

Result array:

My Matlab code looks now as following:
% Replace MaterialIndex with effective colors
[ispresent, idx] = ismember(I1, ColorsIndexed(:,2));
I1(ispresent) = ColorsIndexed(idx(ispresent), 1);
% --------------------------------------------------------
% Replace MaterialIndex with effective colors
[ispresent, idx] = ismember(I2, ColorsIndexed(:,2));
I2(ispresent) = ColorsIndexed(idx(ispresent), 1);
I did it this way as I was unable to loop this operation. How can I loop this for I(n) arrays?
Best regards
4 Comments
Stephen23
on 9 Oct 2020
"how can I now use this for an "n" amount of arrays? Is there no loop necessary? I may can have 'I1' - 'I30', or 'I1' - 'I100'"
Numbering variables like that is a sign that you are doing something wrong.
Putting meta-data (like pseudo-indices) into variable names is a sign that you are doing something wrong.
Accessing badly designed data which is stored in lots of separate variables forces you into writing slow, complex, inefficient, buggy, difficult to debug code:
In most cases the simple, efficient, and recommended alternative is to use indexing into one variable (which could be a container array, e.g. a cell array or a table).
Answers (1)
Star Strider
on 8 Oct 2020
Try this:
ColorIndexed = [compose("%.4f %.4f %.4f", rand(145,3)), compose("%3d",(1:145).')]; % Create String Array
I1 = compose("%d",randi(145,1,402)); % Create String Aray
I2 = ColorIndexed(sscanf(char(I1),'%3d'),1); % Use Indexing To Assign Colours
.
4 Comments
Star Strider
on 8 Oct 2020
I wrote code for 1 array. For ‘n’ arrays, you would need to loop through the arrays and do the same as I did for each one.
Please do not use the eval function! I have absolutely no idea what you are doing in the loop you posted, however I am reasonably confident that there is a much better and more efficient way to do it.
For example, put all the different arrays in a cell array (the cat function is likely appropriate here), and then just index them in the loop. Store the output in a matching cell array, created with a slightly different name for each of the result arrays so as not to over-write the original cell array of string arrays.
See Also
Categories
Find more on Matrix Indexing 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!

