Replacing repeated values of cell with empty [] - MATLAB - arrays

So I have a 1x348 cell composed of numbers and empty brackets. Ie ... [] [] [] [169] [170] [170] [170] [171] [172] [] []...
All what I want to do is change the repeated numbers to empty brackets []. I need to hold the places. I tried this, but am not having any success. It is also not ideal, because in the case with more than one repeat, it would just replace every other repeat with [].
for jj = 1:length(testcell);
if testcell{jj} == testcell{jj-1}
testcell{jj} = []
end
Any help would be greatly appreciated :-)

Lets assume you have {1,1,1}. First iteration will change this to {1,[],1} and second iteration does not see any repetition. Thus iterating backwards is probably the easiest solution:
for jj = length(testcell):-1:2
if testcell{jj} == testcell{jj-1}
testcell{jj} = [];
end
end
Then the first step will result in {1,1,[]} and the second in {1,[],[]}

The only thing your code lacks is some variable to store current value:
current = testcell{1};
for jj = 2:length(testcell)
if testcell{jj} == current
testcell{jj} = [];
else
current = testcell{jj};
end
end
But it's better to use Daniel's solution =).

Alternatively, you could use NaN values to represent cells with empty matrices, and vectorize your code:
testcell(cellfun('isempty', testcell)) = {NaN};
[U, iu] = unique([testcell{end:-1:1}]);
testcell(setdiff(1:numel(testcell), numel(testcell) - iu + 1)) = {NaN};
testcell(cellfun(#isnan, testcell)) = {[]};

Related

Search and replace string in 2D Array in Swift

Teaching myself swift, so complete noob here, but I'm far into a project and just know there must be an easier way to achieve something.
I have a 2D array:
var shopArray = [
["theme":"default","price":0,"owned":true,"active":true,"image":UIImage(named: "defaultImage")!,"title":"BUY NOW"],
["theme":"red","price":1000,"owned":false,"active":false,"image":UIImage(named: "redImage")!,"title":"BUY NOW"],
["theme":"blue","price":2000,"owned":false,"active":false,"image":UIImage(named: "blueImage")!,"title":"BUY NOW"],
["theme":"pool","price":3000,"owned":true,"active":false,"image":UIImage(named: "blueImage")!,"title":"BUY NOW"],
["theme":"line","price":4000,"owned":false,"active":false,"image":UIImage(named: "lineImage")!,"title":"BUY NOW"],
["theme":"neon","price":5000,"owned":false,"active":false,"image":UIImage(named: "lineImage")!,"title":"BUY NOW"]]
Where I simply want to create a function that runs and search for all the "owned" keys and make them all "false".
How do you search and replace in Arrays / 2D Arrays. More specifiaclly, what should the func look like?
Thank you!
You don't have a 2D array, you have an Array of Dictionaries.
You can set all of the values for the owned keys by iterating the indices of the Array and updating the values:
shopArray.indices.forEach { shopArray[$0]["owned"] = false }
That is the functional way to do it. You could also do the same operation with a for loop:
for idx in shopArray.indices {
shopArray[idx]["owned"] = false
}
You could do something like this to loopthrough the array replacing the approriate element.
var i = 0
for x in shopArray {
var y = x
y["owned"] = false
shopArray.remove(at: i)
shopArray.insert(y, at: i)
i = i + 1
}
or you could use a while loop to do the same with less code lines.
var y = 0
while y < shopArray.count {
shopArray[y].updateValue(false, forKey: "owned")
y += 1
}
There is proably somthing doable with .contains, but I'm not sure you need that toachive the result you mention above. Play around in a play ground in xcode and try a few different options without doing anything that might cause issues in your project.

finding a str in MatLab cells

I am currently using MatLab R2014a
I have one array and one cell:
MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1};
MyArray consists of code names that are repeatable throughout MyCell.
I would like to check if any of the strings in MyArray are in MyCell and if it is, save the name to a new cell.
For now I have:
NewCell = {};
for i = 1:length(MyCell)
for j = 1:length(MyArray)
Find = strfind(MyCell(i), MyArray)
if ~isempty(Find)
NewCell = {NewCell; MyCell(j)}
end
end
end
However, when I use strfind I get this error message:
Undefined function 'strfind' for input arguments of type 'char'
If I use strcmp instead of strfind, I get an array of everything in MyCell repeated by the number of elements in MyArray.
My Ideal output would be:
NewCell1 = {'Name1AA1', 'Name2AA1'}
NewCell2 = {'Name4AB2'}
NewCell3 = {'Name3Acc2'}
ie, no new cell for the code names that are not present in MyArray or no new cell if there is a code name in MyArray but not in MyCell.
Any help is welcome, and thanks for your time
You can use a combination of regular expressions to achieve the desired output. Your approach of wanting to name variables dynamically is not recommended and will lead to code which is harder to debug. Use indexing instead.
You can read this informative post on Matlab's forum to understand why.
%Your input data.
MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1'};
%Find common elements between MyArray and MyCell.
elem = cellfun(#(x) regexp(MyArray,x(end-2:end),'match'),MyCell,'un',0);
%Eliminate duplicates.
NewCell = unique([elem{:}]);
%Find elements in MyCell which end with NewCell elements and group them.
NewCell = cellfun(#(x) regexp([MyCell{:}],strcat('Name\d\w?',x),'match'),NewCell,'un',0);
%Join elements.
NewCell{1} = {strjoin(NewCell{1},''',''')};
NewCell{1} = {'Name1AA1','Name2AA1'}
NewCell{2} = {'Name4AB2'}
NewCell{3} = {'Name3Acc2'}

Index Subset of Array in For Loop in MATLAB

I have a question regarding indexing and loops in MATLAB. I have a vector of length n (named data in the code below). I want to examine this vector 4 elements at a time inside of a for loop. How can I do this? My attempt included below does not work because it will exceed the array dimensions at the end of the loop.
for k = 1:length(data)
index = k:k+3;
cur_data = data(index);
pre_q_data1 = cur_data(1);
pre_q_data2 = cur_data(2);
% Interweaving the data
q = [pre_q_data1; pre_q_data2];
qdata = q(:)';
pre_i_data1 = cur_data(3);
pre_i_data2 = cur_data(4);
i = [pre_i_data1; pre_i_data2];
idata = i(:)';
end
You shouldn't have k go all the way to length(data) if you're planning on indexing up to k+3.
I've also taken the liberty of greatly simplifying your code, but feel free to ignore that!
for k = 1:length(data)-3
% maximum k = length(data)-3, so maximum index = length(data)-3+3=length(data)
index = k:k+3;
cur_data = data(k:k+3);
% Interweaving the data
q = cur_data(1:2); % transpose at end of line here if need be
i = cur_data(3:4); % could just use data(k+2:k+3) and not use cur_data
end

Efficient method of merging two neighboring indicies in Scala

What would be a most efficient method of merging two neighboring indicies in Scala? What I have in mind a nasty while loops with copying.
For example, there's a buffer array A, with length N. The new array need be generated such that for A(i) = A(i) + A(i+1), where i < N
For example, merging and summing the second and third element, and generate a new array.
ArrayBuffer(1,2,4,3) => ArrayBuffer(1,6,3)
UPDATE:
I think I come up with some solution, but doesn't like it much. Any suggestion to improve would be highly appreciated.
scala> val i = 1
i: Int = 1
scala> ArrayBuffer(1,2,4,3).zipWithIndex.foldLeft(ArrayBuffer[Int]())( (k,v)=> if(v._2==i+1){ k(k.length-1) =(k.last+v._1);k; }else k+= v._1 )
The simplest way to get neighbors is to use sliding method.
a.sliding(2, 1).map(_.sum)
where the first argument is a size and the second one is step.
If you want to keep the first and the last element intact something like this should work:
a.head +: a.drop(1).dropRight(1).sliding(2, 1).map(_.sum).toArray :+ a.last
If you want to avoid copying and array on append/prepend you can rewrite it as follows:
val aa = a.sliding(2, 1).map(_.sum).toArray
aa(0) = a.head
aa(aa.size - 1) = a
or use ListBuffer which provides constant time prepend and append.
It should be also possible to use Iterators:
val middle: Iterator[Int] = a.drop(1).dropRight(1).sliding(2, 1).map(_.sum)
(Iterator(a.head) ++ middle ++ Iterator(a.last)).toArray // or toBuffer

Find Specific Array Using a Loop

I'm incredibly new to swift and I'm sure this question has been asked before, but I have no idea of the terminology of what to search.
I've seen how to do this before, but not sure where. I want to be able to loop though my arrays using a count, like the below (but that is not working). So the last number of the array name changes depending on the count. So if myCount = 0 then myArray will equal array_0001_00 and if my count = 6 then myArray will equal array_0001_06, and so on.
I'm not sure if I'm missing something small or if I'm completely on the wrong track.
let array_0001_00 = [102,102,102,102,102,102,102,102]
let array_0001_01 = [112,112,112,112,112,112,112,112]
myArray = array_0001_0\(myCount)
Any help would be much appreciated. Thanks.
I'm currently using the below, which works, but is creating a mountain of code:
if myCount == 0 {
myArray = array_0001_00
} else if myBuilderCountY == 1 {
myArray = array_0001_01
}
I hope I haven't misunderstood - you have a number of arrays, and you want to select one of them using an index. That looks like selecting an element from an array:
let array_0001_00 = [102,102,102,102,102,102,102,102]
let array_0001_01 = [112,112,112,112,112,112,112,112]
let array_0001_02 = [122,122,122,122,122,122,122,122]
let array_of_arrays = [
array_0001_00,
array_0001_01,
array_0001_02
]
let index = 1
let myArray = array_of_arrays[index] // This assigns (a copy of) array_0001_01

Resources