sorting 1d array in VB - arrays

I wrote a 1D array sorting code, however the first value disappears after sorting. Here is my code:
For i = 0 To 10 - 1
For j = 0 To (10 - 1) - i
If Xs(j) > Xs(j + 1) Then
tmp = Xs(j)
Xs(j) = Xs(j + 1)
Xs(j + 1) = tmp
End If
Next j
Next i
Original array:
0.995136318967065
1.92659411953677E-02
0.075211466386023
0.276865639306513
0.796949177428061
0.644136557566409
0.912439108707731
0.318021611061513
0.863316048056547
0.469710111256482
Array after sorting:
0
1.92659411953677E-02
0.075211466386023
0.276865639306513
0.318021611061513
0.469710111256482
0.644136557566409
0.796949177428061
0.863316048056547
0.912439108707731

I suspect you have dimensioned your array 0 To 10:
Dim Xs(0 To 10)
so creating 11 spaces into it. However, you have only 10 of them so you will have an Empty cell that will put itself on the first position at some point of the loop (being it evaluated as 0, which is indeed the lowest value into your dataset).
I also believe you have dimensioned your array 0 To 10 instead of 0 To 9 because, if not, you would have got an Subscript out of range error in this part of the code:
For j = 0 To (10 - 1) - i
In order to make your code work:
a) Change the Dim Xs(0 To 10) to Dim Xs(0 To 9)
b) Change the For j = 0 To (10 - 1) - i to For j = 0 To (10 - 1) - i-1

Related

How can I find the nonzero values in a MATLAB cells array?

The following code generates an cell array Index [1x29], where each cell is an array [29x6]:
for i = 1 : size(P1_cell,1)
for j = 1 : size(P1_cell,2)
[Lia,Lib] = ismember(P1_cell{i,j},PATTERNS_FOR_ERANOS_cell{1},'rows');
Index1(i,j) = Lib % 29x6
end
Index{i} = Index1; % 1x29
end
How can I find the nonzero values in Index array?, i.e. generate an array with the number of non-zero values in each row of the Index1 array. I tried the following loop, but it doesn't work, it creates conflict with the previous one:
for i = 1 : length(Index)
for j = 1 : length(Index)
Non_ceros = length(find(Index{:,i}(j,:))); %% I just need the length of the find function output
end
end
I need help, Thanks in advance.
The nnz() (number of non-zeros) function can be used to evaluate the number of non-zero elements. To obtain the specific positive values you can index the array by using the indices returned by the find() function. I used some random test data but it should work for 29 by 6 sized arrays as well.
%Random test data%
Index{1} = [5 2 3 0 zeros(1,25)];
Index{2} = [9 2 3 1 zeros(1,25)];
Index{3} = [5 5 5 5 zeros(1,25)];
%Initializing and array to count the number of zeroes%
Non_Zero_Counts = zeros(length(Index),1);
for Row_Index = 1: length(Index)
%Evaluating the number of positive values%
Array = Index{Row_Index};
Non_Zero_Counts(Row_Index) = nnz(Array);
%Retrieving the positive values%
Positive_Indices = find(Array);
PositiveElements{Row_Index} = Array(Positive_Indices);
disp(Non_Zero_Counts(Row_Index) + " Non-Zero Elements ");
disp(PositiveElements{Row_Index});
end
Ran using MATLAB R2019b
for i = 1 : length(Index)
for j = 1 : length(Index)
Non_ceros(i,j) = nnz(Index{:,i}(j,:));
end
end

Vectorizing a code that requires to complement some elements of a binary array

I have a matrix A of dimension m-by-n composed of zeros and ones, and a matrix J of dimension m-by-1 reporting some integers from [1,...,n].
I want to construct a matrix B of dimension m-by-n such that for i = 1,...,m
B(i,j) = A(i,j) for j=1,...,n-1
B(i,n) = abs(A(i,n)-1)
If sum(B(i,:)) is odd then B(i,J(i)) = abs(B(i,J(i))-1)
This code does what I want:
m = 4;
n = 5;
A = [1 1 1 1 1; ...
0 0 1 0 0; ...
1 0 1 0 1; ...
0 1 0 0 1];
J = [1;2;1;4];
B = zeros(m,n);
for i = 1:m
B(i,n) = abs(A(i,n)-1);
for j = 1:n-1
B(i,j) = A(i,j);
end
if mod(sum(B(i,:)),2)~=0
B(i,J(i)) = abs(B(i,J(i))-1);
end
end
Can you suggest more efficient algorithms, that do not use the nested loop?
No for loops are required for your question. It just needs an effective use of the colon operator and logical-indexing as follows:
% First initialize B to all zeros
B = zeros(size(A));
% Assign all but last columns of A to B
B(:, 1:end-1) = A(:, 1:end-1);
% Assign the last column of B based on the last column of A
B(:, end) = abs(A(:, end) - 1);
% Set all cells to required value
% Original code which does not work: B(oddRow, J(oddRow)) = abs(B(oddRow, J(oddRow)) - 1);
% Correct code:
% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
for ii = 1:numel(oddRow)
B(oddRow(ii), J(oddRow(ii))) = abs(B(oddRow(ii), J(oddRow(ii))) - 1);
end
I guess for the last part it is best to use a for loop.
Edit: See the neat trick by EBH to do the last part without a for loop
Just to add to #ammportal good answer, also the last part can be done without a loop with the use of linear indices. For that, sub2ind is useful. So adopting the last part of the previous answer, this can be done:
% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
% convert the locations to linear indices
ind = sub2ind(size(B),oddRow,J(oddRow));
B(ind) = abs(B(ind)- 1);

A simple sorting algorithm

This is a simple sorting function that I wrote in Matlab:
function [matrix] = sorting(matrix)
for index = 1:length(matrix)-1
if matrix(index) > matrix(index + 1)
temp = matrix(index + 1);
matrix(index + 1) = matrix(index);
matrix(index) = temp;
end
end
check_sorted(matrix)
end
function [matrix] = check_sorted(matrix)
count = 0;
for index = 1:length(matrix)-1
if matrix(index) < matrix(index + 1)
count = count + 1;
end
end
if count+1 < length(matrix)
sorting(matrix);
end
end
The input for sorting function is a 1D array, e.g. [4 3 2 1], and it successfully returns the sorted array [1 2 3 4] for the first time I call it, but then it starts to return unsorted arrays?
You've got a missing semicolon that is causing the results of each call to check_sorted to be displayed, which is confusing things. If you add the semicolon, the output from sorting with the array [2 4 1 3] suggested in the comments is:
>> sorting([2 4 1 3])
ans =
2 1 3 4
Clearly this isn't sorted. The problem is that MATLAB passes function arguments by value, not by reference. Since you're not returning the re-sorted matrix from check_sorted or updating the return matrix in sorting the original matrix never gets updated. You need to change at least one line in each function (changed lines are commented):
function [matrix] = check_sorted(matrix)
count = 0;
for index = 1:length(matrix)-1
if matrix(index) < matrix(index + 1)
count = count + 1;
end
end
if count+1 < length(matrix)
matrix = sorting(matrix); % change: return re-sorted matrix
end
end
function [matrix] = sorting(matrix)
for index = 1:length(matrix)-1
if matrix(index) > matrix(index + 1)
temp = matrix(index + 1);
matrix(index + 1) = matrix(index);
matrix(index) = temp;
end
end
matrix = check_sorted(matrix); % change: return checked matrix
end
Now the matrix will be updated if it is not sorted on the first (or any subsequent) pass and the fully sorted matrix will be returned by sorting.
This is an odd sort of recursion that really isn't necessary. If you change check_sorted to return a boolean value, true for sorted, false for not sorted, you can change that recursion to a while loop around the for loop in sorting:
function [TF] = check_sorted2(matrix)
count = 0;
for index = 1:length(matrix)-1
if matrix(index) < matrix(index + 1)
count = count + 1;
end
end
TF = count+1 == length(matrix); % TF = true if matrix is sorted
% TF = false otherwise
end
function [matrix] = sorting2(matrix)
while ~check_sorted2(matrix) % keep going until matrix is sorted
for index = 1:length(matrix)-1
if matrix(index) > matrix(index + 1)
temp = matrix(index + 1);
matrix(index + 1) = matrix(index);
matrix(index) = temp;
end
end
end
end
Of course the whole thing can be optimized and vectorized, but this will at least get you going.
i tested your algorithms and it worked. so something else might be wrong. but this algorithm is very very inefficient. you may google sort and pick one that suits you.
if you really want to stick with the algorithm, you could improve it by shortening the two loops. for example, after first call to sorting, for each subsequent call to sorting, you could shorten the loop cycle by 1 because the first call to sorting would put the largest number to the end of the array, the second call would put the second largest to the second from the end, and so on. this is so called bubble sorting. also in check_sorted, you don't need to go through the entire length of the array to check if the array has been sorted. as soon as you see matrix(index) > matrix(index + 1), you can immediately exit the loop (after you set a flag to indicate the array hasn't been sorted).

VBScript loop advice

sqlRows = rst.GetRows()
i = 0
For Each element In sqlRows
If i > 0 And i < sizeOfState + 1 Then
SmartTags("visu_state_on")(i - 1) = element
ElseIf i > sizeOfState And i < 2 * sizeOfState + 1 Then
SmartTags("visu_state_off")(i - sizeOfState - 1) = element
ElseIf i > (2 * sizeOfState ) And i < 2 * sizeOfState + sizeOfMeasurement + 1 Then
SmartTags("visu_limits_right")(i - (2 * sizeOfState - 1)) = element
ElseIf i > 2 * sizeOfState + sizeOfMeasurement And i < 2 * (sizeOfStanja + sizeOfMeasurement ) + 1 Then
SmartTags("visu_limits_left")(i - (2 * sizeOfState + sizeOfMeasurement )) = element
End If
i = i + 1
Next
With code above I'm looping through array sqlRows and with variable i I'm filling other four arrays with data from sqlRows.
This solution works but I'm wondering is there more elegant way to achieve the same.
sqlRows is array with dimensions 343x1,
visu_state_on is array with dimensions 8x1,
visu_state_off is array with dimensions 8x1,
visu_limits_right is array with dimensions 160x1,
visu_limits_left is array with dimensions 160x1,
and variables sizeOfState and sizeOfMeasurement are just there that I can calculate indexes for these four arrays.
For one thing you can remove the first clause from each of your conditions, because they will always be true
i starts with the value 0 and is always incremented, so the value will never be less than zero.
If a value is not less than n + 1 (condition in previous ElseIf) then it's guaranteed to be greater than n.
Also, VBScript does have a <= comparison operator, so it's better to compare i <= n rather than i < n + 1.
I would also recommend calculating values that won't change inside the loop just once outside the loop. Re-calculating them with each loop cycle is a waste of resources.
Adding an Else branch to handle values greater than 2 * (sizeOfStanja + sizeOfMeasurement) might be a good idea too.
sqlRows = rst.GetRows()
i = 0
ref1 = 2 * sizeOfState
ref2 = ref1 + sizeOfMeasurement
ref3 = 2 * (sizeOfStanja + sizeOfMeasurement)
For Each element In sqlRows
If i <= sizeOfState Then
SmartTags("visu_state_on")(i - 1) = element
ElseIf i <= ref1 Then
SmartTags("visu_state_off")(i - sizeOfState - 1) = element
ElseIf i <= ref2 Then
SmartTags("visu_limits_right")(i - ref1 + 1) = element
ElseIf i <= ref3 Then
SmartTags("visu_limits_left")(i - ref2) = element
Else
'handle i > ref3 here
End If
i = i + 1
Next

MATLAB: Finding the entry number of the first '1' in a logical array

I have created a logical array of 1's and 0's using the following code:
nWindow = 10;
LowerTotInitial = std(LowerTot(1:nWindow));
UpperTotInitial = std(UpperTot(1:nWindow));
flag = 0;
flagArray = zeros(length(LowerTot), 1);
for n = 1 : nData0 - nWindow
for k = 0 : nWindow - 1
if LowerTot(n + k) < 0.1*LowerTotInitial || UpperTot(n + k) < 0.1*UpperTotInitial
flag = 1;
flagArray(n) = 1;
else
flag = 0;
end
end
end
This returns flagArray, an array of 0's and 1's. I am trying to find the index of the first 1 in the array. ie. 1 = flagArray(index). I am confused as to what is the best way to accomplish this!
What you call an entry number is referred to as an index in MATLAB-speak. To find the index of the first matching element in an array you can use the FIND function:
>> x = [0 0 1 0 1 0];
>> find(x, 1, 'first')
ans =
3
Try this ind = find(flagArray, k, 'first')
with k =1
Read this Matlab Docs - find

Resources