Matlab changing array value in error when appending matrices - arrays

I have a very strange bug in MATLAB (R2016a) where appending a ones array using vertcat (or using regular appending with [A; B]) results in a matrix where the ones have been scaled down to 0.0001 instead of 1. Multiplying the ones matrix by 10000 fixes the issue but I would like to know why 0.0001 is being appended instead of 1. Here is the code:
temp = ones([1,307200]);
new_coords = vertcat(world_coords, temp);
new_coords
which results in columns like the following being outputted:
0.4449
0.3673
1.8984
0.0001
The type for world_coords is double, so I don't think typecasting is the issue.

As mentioned in my comment, the output is scaled due to the range of the the values in world_coords. You should see in the first line of the output a scaling factor of 1.0e+4.
You can change the output format for example with:
format long
For more details see: format

Related

How to count for 2 different arrays how many times the elements are repeated, in MATLAB?

I have array A (44x1) and B (41x1), and I want to count for both arrays how many times the elements are repeated. And if the repeated values are present in both arrays, I want their counting to be divided (for instance: value 0.5 appears 500 times in A and 350 times in B, so now divide 500 by 350).
I have to do this for bigger arrays as well, so I was thinking about using a looping (but no idea how to do it on MATLAB).
I got what I want on python:
import pandas as pd
data1 = pd.read_excel('C:/Users/Desktop/Python/data1.xlsx')
data2 = pd.read_excel('C:/Users/Desktop/Python/data2.xlsx')
for i in data1['Mag'].value_counts() & data2['Mag'].value_counts():
a = data1['Mag'].value_counts()/data2['Mag'].value_counts()
print(a)
break
Any idea of how to do the same on MATLAB? Thanks!
Since you can enumerate all valid earthquake magnitude values, you could use:
% Make up some data
A=randi([2 58],[100 1])/10;
B=randi([2 58],[20 1])/10;
% Round data to nearest tenth
%A=round(A,1); %uncomment if necessary
%B=round(B,1); %same
% Divide frequencies
validmags=0.2:0.1:5.8;
Afreqs=sum(double( abs(A-validmags)<1e-6 ),1); %relies on implicit expansion; A must be a column vector and validmags must be a row vector; dimension argument to sum() only to remind user; double() not really needed
Bfreqs=sum(double( abs(B-validmags)<1e-6 ),1); %same
Bfreqs./Afreqs, %for a fancier version: [{'Magnitude'} num2cell(validmags) ; {'Freq(B)/Freq(A)'} num2cell(Bfreqs./Afreqs)].'
The last line will produce NaN for 0/0, +Inf for nn/0, and 0 for 0/nn.
You could also use uniquetol, align the unique values of each vector, and divide the respective absolute frequencies. But I think the above approach is cleaner and easier to understand.

Creating a linearly spaced array of a particular size

I am new to MATLAB and currently working on my homework assignment. I am trying to declare the x variable as the following:
Create a linearly spaced array x of size (1 × 200) comprising values ranging from –pi to pi.
I've tried this code:
x=[-pi:200:pi];
but I'm not sure if it's the correct way to do this or not.
You can use linspace as follow:
x = linspace(-pi, pi, 200);
check this out for an example:
https://www.mathworks.com/help/matlab/ref/linspace.html
The other answer shows how to use linspace, this is the correct method.
But you can also use the colon operator and some simple arithmetic to do this:
x = -pi : 2*pi/199 : pi -- This means: go from -π to π in steps of such a size that we get exactly 200 values.
x = (0:199) * (2*pi/199) - pi -- This means: create an array with 200 integer values, then scale them to the right range.
Note that you shouldn't use square brackets [] here. They are for concatenating arrays. The colon operator creates a single array, there is nothing to concatenate it with.

Generating Image From Cell Array Using Imagesc Matlab

I have a cell array (3 x 4), called output, containing a 1024 x 1024 matrix in each cell. I want to plot the 4 matrices in ouput{1,:}. Furthermore, I have a structure, called dinfo, which correspondingly contains the names of each matrix (field with matrix names = "name"). I want each image to be titled with its name. Here is the code I have written thus far:
for i = 1:length(output{1,:})
figure
imagesc(output{1,i});
colormap('jet')
colorbar;
title(num2str(dinfo.name(i)))
end
I keep getting the error that "length has too many input arguments". If I change the code to avoid the length function-related error:
for i = 1:4
figure
imagesc(output{1,i});
colormap('jet')
colorbar;
title(num2str(dinfo.name(i)))
end
I get the error, "Expected one output from a curly brace or dot indexing expression, but there were 4 results".
Any thoughts on how I could resolve both of these errors?
Thank you for your time :)
output{1,:} is a comma-separated list; it contains the 1024 matrices of the first row of output, so length has 1024 arguments. The best way to obtain the number of columns is using size(...,2):
for i = 1:size(output,2)
figure
imagesc(output{1,i});
colormap('jet')
colorbar;
end
As for the second error, there is something wrong with dinfo.name; probably, it is also a comma-separated list because dinfo is a structure array. Try using dinfo(i).name instead of dinfo.name(i).

Using hist in Matlab to compute occurrences

I am using hist to compute the number of occurrences of values in a matrix in Matlab.
I think I am using it wrong because it gives me completely weird results. Could you help me to understand what is going on?
When I run this piece of code I get countsB as desired
rng default;
B=randi([0,3],10,1);
idxB=unique(B);
countsB=(hist(B,idxB))';
i.e.
B=[3;3;0;3;2;0;1;2;3;3];
idxB=[0;1;2;3];
countsB=[2;1;2;5];
When I run this other piece of code I get wrong results for countsA
A=ones(524288,1)*3418;
idxA=unique(A);
countsA=(hist(A,idxA))';
i.e.
idxA=3148;
countsA=[zeros(1709,1); 524288; zeros(1708,1)];
What am I doing wrong?
To add to the other answers: you can replace hist by the explicit sum:
idxA = unique(A);
countsA = sum(bsxfun(#eq, A(:), idxA(:).'), 1);
idxA is a scalar, which means the number of bins in this context.
setting idxA as a vector instead e.g. [0,3418] will get you a hist with bins centered at 0 and 3418, similarly to what you got with idxB, which was also a vector
I think it has to do with:
N = HIST(Y,M), where M is a scalar, uses M bins.
and I think you are assuming it would do:
N = HIST(Y,X), where X is a vector, returns the distribution of Y
among bins with centers specified by X.
In other words, in the first case matlab is assuming that you are asking for 3418 bins

Empty find matlab

I am trying to find what's the number on the array for the 1000 value. This is my code:
size = linspace(420, 2200, 100000);
size1000 = find(size==1000);
It returns an empty variable for size 1000. If I actually change 1000 with 420 it actually returns 1 like it should. Why is this not working?
The result of find is empty because 1000 is not in the array and isn't expected to be. Using the inputs to linspace, your expected step size is going to be 0.0178
(2200 - 420) / 100000
% 0.0178
With this step size and a starting value of 420, you're never going to hit the value 1000 exactly. The closest values in the array are 1000.001 and 999.983. If you want to identify values that are close to 1000, you can do something like the following instead.
inds = find(abs(size - 1000) < 0.01);
As a side-note, do not use size as the name of a variable since that is the name of a built-in MATLAB function and using it as a variable name can result in unexpected behavior.
You can also use logical indexing to simply remove all of the values below 1000, and then you know that the first component of what is left will be your answer....
a = size(size>1000);
a(1)
For what it is worth, please PLEASE do not use size as a variable name. size is an important MATLAB function to get the size of a matrix. For example,
>> size(randn(2,3))
ans =
2 3
However, when you declare a variable named size, like you do in your code, you will hide this function. So now, at some point later in your code, if you called size(randn(2,3)), you will get the cryptic error
Subscript indices must either be real positive integers or
logicals.
These are extremely tricky to track down, so please avoid it.

Resources