/r/matlab
Official MATLAB subreddit
MATLAB news, code tips and tricks, questions, and discussion! We are here to help, but won't do your homework or help you pirate software.
The effort you put into asking a question is often matched by the quality of our answers.
Try saturnapi to share and run MATLAB code in a web browser!
If you want flair simply Message the mods
/r/matlab
Hello, I am making project in school, model simulation model of PID control of fan. I don't understand, why in scopes the constant is 0 or close to zero when it should be 900. Please help I am lost.
I'm playing around with importing coordinates into Solidworks. I start in MATLAB and make the graph (which is half the shape) --> export to Excel --> import to Solidworks. I want to take something like graph in the screenshot and mirror it over the x axis.
I want to use a function to make a line in the (x,y) space and use the same function in the (x, -y) space to make a closed entity.
I tried this:
set(gca,'xdir','reverse','ydir','reverse')
It worked fine but it moved it from the original position.
Maybe flipud or flip?
Hello,
I am struggling with a problem I have. I have an excel sheet with data that I am reading in and analyzing. I am reading it all into a single cell matrix.
Within the matrix of raw data, I have all different types from doubles to strings to char.
Well several parts of the data have 'nan' and other parts are recognized as a proper NaN value. I am trying to add code to find all cells with 'nan' and replace it with the proper NaN value. This is important as part of my script uses isnan(data) and these 'nan' cells are returning a 1x3 logical array of zeros.
Also, given that the matrix has different types within it, I can't simply convert the entire matrix with cell2mat or whatnot. It messes up other parts of the data. So I only want to change the specific cells that have 'nan' in them.
I am trying to do this without having to create two nested for loops. Is there a way?
If not, is there a more "elegant" way than having many lines of nested for loops and instead use cellfun or another method?
I greatly appreciate any help and insight.
Thank you.
Edited to add:
Here is the code I wrote that works but I do not want such an un-elegant solution. Trying to improve my coding ability and even though this works, it looks ugly.
"
xyData = size(data);
for i = 1:xyData(1)
for j =1:xyData(2)
if length(raw{i,j} == 3
if raw{i,j} == 'nan'
raw{i,j] = NaN
end
end
end
end
"
For some reason it won't let me indent or put spaces at the beginning of a line here.
I really want to learn and understand how to do this in a more concise way, please.
Hi. I have an upcoming 4-hour interview with Mathworks for a full time EDG role for Master/PhD graduates in signal processing/robotics.
Can someone share their experience? How much coding will be expected? Any tips for the technical session will be greatly appreciated. Thanks.
Hello everyone,
I'm working on a Simulink model and I have a couple of questions I hope someone might be able to help me with.
Any suggestions or insights would be greatly appreciated!
Sharing video and code on how to filter a signal using a sliding window.
Hello,
I am quite new at FPGA programming and I am currently trying to implement an algorithm on an Xilinx RFSoC ZCU111 platform. I am using the HDL Coder and SoC Blockset in Simulink to design and generate Verilog code.
My design works fine in SIMULINK but my I am confused on how to go about transmitting data from Matlab Workspace into the PS memory on hardware. My current design uses the 'From Workspace' block to send data to the PS memory for Streaming to the FPGA. I have attached an image of the implementation.
My question is, is this approach feasible enough to be used to test data on hardware once bitstream is generated? Do I need to make some modifications to test my design on hardware ?
I am very new to Matlab and my job gave me a DAC to mess around with so I that I could teach myself Matlab code. Normally I use LabVIEW 😑. I just need some basic help with this CMD code.
fprintf(SW, 'SOURce:DIGital:DATA:BYTE 0,(@101)');
What I am trying to figure out is how to inject a variable for the address (@101) so that I can loop through all the addressed.
If this is not an effective way to do this, please tell me 😊.
If you want to share your MATLAB apps with others on the web, there is an interesting blog post that discuss how to do it with MATLAB Online.
Here is an example from the blog post. Check out the link for more details.
If you want to share your MATLAB apps with others on the web, there is an interesting blog post that discuss how to do it with MATLAB Online.
Here is an example from the blog post. Check out the link for more details.
The interoperability between MATLAB and Python is getting better all the time. In my latest article I show how easy it is to use MATLAB matrices in Numpy functions. For example
% Create a MATLAB array
matlabArray = rand(5)
% Pass it to a Numpy functionpy
Eig = py.numpy.linalg.eigvals(matlabArray)
It's also pretty easy to use Numpy arrays in MATLAB functions although there are a few conversion shenanigans required. Details in the blog post
https://blogs.mathworks.com/matlab/2024/12/05/numpy-in-matlab/
I have a mf4-file with a bunch of CAN Bus signals, but I can’t for the life of me figure out how to write a simple script, that lists all the signals it can find in a loaded mf4-file. Can’t find any help in the official docs. I just need to extract data that corresponds to a certain signal. Is there a function to do that?
I’m trying to calculate the Young’s modulus on Matlab does anyone have a code I can use?
I literally cannot run the code, I ran it through ChatGPT to see if i made any mistakes and it says it is fine, i literally do not know what to do. When i push run it just makes this error sounding beep sound and then does nothing, no warning messages pop up or anything just nothingness
If I want to load a text file as a matrix into MATLAB, how can I exclude the first few rows of the text file? For example, I have a frequency analysis and when the file is created, the first few lines are the date, time, and then variables. If I only want the numbers, how can this be done?
I have a large multi-dimensional matrix of binary data stored in MATLAB that needs to be written to disk and then read into a C++ program at a later point in time.
I am currently reading the data in the C++ program "backwards" to handle the fact that in MATLAB fwrite writes the data in column major order, but C++ wants the data in row major order.
Another alternative I was considering was to reshape the data to be row major order in MATLAB (by calling reshape), before calling fwrite, and then reading in the binary data as usual in C++.
I don't want to write out the data one element at a time because of how slow that makes the MATLAB code run, as the matrix is 10 Dimensional and on the order of hundreds of megabytes.
Are there other simpler alternatives that anyone has done?
I use Linux mint and I tried to run it in bottles. I dont have a license, I found a free to download matlab but I cant install it. In bottles I use Wine-9.0. When i am trying to run it I see this.
Sorry for my bad english.
Hi everyone, I'm working with a recurrent neural network in MATLAB, and I want to clarify the difference in predictions when using two different methods:
Calling predict(net, X) directly with the entire input sequence.
Iteratively updating the state of the network by looping through each time step and feeding the inputs one by one (e.g., net= predictAndUpdateState(net, X) for each step, or something like (as suggested in newer versions):
net=resetState(net);
for i=1:input_sequence_length [predictions,state]=predict(net,X(i,:)); net.State=state; end
Are the predictions from these two approaches supposed to be identical? I tried with my own network for ts forecasting: the predictions are more or less identical (negligible differences), but not equal. What does this could mean? Does it mean that the "state" of the network does not have an important role on the predictions? Thanks in advance for your suggestions!
error: Conversion to logical from sym is not possible.
I have a function caller block in my model which calls a function. The function definition is present in another c code file. How to make matlab understand the linkage between these files? I tried to add the .c file in custome code section in configuration parameter settings. But its not working
I have a function caller block in my model which calls a function. The function definition is present in another c code file. How to make matlab understand the linkage between these files? I tried to add the .c file in custome code section in configuration parameter settings. But its not working
Hello All, I am using this MiniHeap to store the priorities and indices for an A* function that I am using, currently this is a functional class that returns the correct path when comparing it to other cost functions. I have been trying to improve the runtime of the insert and extractMin functions by removing the for loops that deals with the obj.positions so that I don't have to sequentially updates the positions. I have run into an issue where I have tried to change obj.positions to a numeric array but I am observing an issue with incorrect paths (the path should not be possible), I was hoping to do a direct update to the obj.positions to cut down on my run time.
edit: I would like to clarify what I mean by incorrect path. As I am doing a cost function comparison of different parameters certain paths found should have the best parameter as the path is only being optimized around said parameter. the only difference in the program that I am using is the two mini heaps below. The one that uses maps provides the "correct" path but is slower. I am trying to improve the performance of my A* function and I know that the bottle neck is in the insert function; specifically in the for loops. I have tried using a direct update approach to improve run time (observed about a 90% reduction when using numeric and cell arrays for the position). I have tried to change the data type of the position from map to dictionary prior to doing direct updates which is where I am seeing the issue of "incorrect" paths.
classdef MinHeap_two
properties
elements
positions
end
methods
function obj = MinHeap_two()
obj.elements = [];
obj.positions = containers.Map('KeyType', 'double', 'ValueType', 'double');
end
function obj = insert(obj, index, priority)
% Check if the index already exists in the heap
if isKey(obj.positions, index)
currentPosition = obj.positions(index);
% Ensure the currentPosition is valid
if currentPosition > 0 && currentPosition <= size(obj.elements, 1)
currentPriority = obj.elements(currentPosition, 1); % Get current priority
% Case 1: New priority is better, remove the old element and insert the new one
if priority < currentPriority
obj.elements(currentPosition, :) = []; % Remove the existing element
obj.positions.remove(index);
% Adjust positions for elements after the removed element
for i = currentPosition:size(obj.elements, 1)
obj.positions(obj.elements(i, 2)) = i;
end
% Clean up the heap after removal
obj = heapifyDown(obj, currentPosition);
[obj, ~] = verifyAndFixMinHeap(obj);
else
% If the current priority is better or the same, no need to insert
return;
end
else
% Case 2: Handle invalid position and potential duplicate log
duplicateCount = 0;
duplicatePosition = -1;
% Check for duplicates in the heap
for i = 1:size(obj.elements, 1)
if obj.elements(i, 2) == index
duplicateCount = duplicateCount + 1;
duplicatePosition = i;
end
end
% Handle duplicate logging
if duplicateCount > 1
currentPriority = obj.elements(currentPosition, 1);
duplicatePriority = obj.elements(duplicatePosition, 1);
% Case 3: If the duplicate has better priority, remove the current element
if duplicatePriority < currentPriority
obj.elements(currentPosition, :) = [];
obj.positions.remove(index);
% Adjust positions after removal
for i = currentPosition:size(obj.elements, 1)
obj.positions(obj.elements(i, 2)) = i;
end
% Clean up after removal
obj = heapifyDown(obj, currentPosition);
else
% Case 4: Otherwise, remove the duplicate
obj.elements(duplicatePosition, :) = [];
obj.positions.remove(index);
% Adjust positions for elements after removal
for i = duplicatePosition:size(obj.elements, 1)
obj.positions(obj.elements(i, 2)) = i;
end
% Clean up after removing duplicate
obj = heapifyDown(obj, duplicatePosition);
end
end
[obj, ~] = verifyAndFixMinHeap(obj);
return;
end
end
% Case 5: Insert the new element at the end of the heap
obj.elements = [obj.elements; priority, index];
obj.positions(index) = size(obj.elements, 1);
% Clean up the heap by "bubbling up" the new element
obj = heapifyUp(obj, size(obj.elements, 1));
[obj, ~] = verifyAndFixMinHeap(obj);
end
function obj = insertbatch(obj, indices, priorities)
% Step 1: Handle conflicts and remove existing elements if necessary
existingIndices = indices(isKey(obj.positions, (indices))); % Filter out existing indices
for i = 1:length(existingIndices)
idx = cell2mat(existingIndices(i));
currentPosition = obj.positions(idx);
% Ensure currentPosition is within bounds before accessing obj.elements
if currentPosition > 0 && currentPosition <= size(obj.elements, 1)
currentPriority = obj.elements(currentPosition, 1); % Current priority
% Get the priority of the new element for this index
newPriority = priorities(cell2mat(indices) == idx);
% If the new priority is better, remove the existing one
if newPriority < currentPriority
obj.elements(currentPosition, :) = []; % Remove existing element
obj.positions.remove(idx);
% Adjust positions after removal
for j = currentPosition:size(obj.elements, 1)
obj.positions(obj.elements(j, 2)) = j;
end
else
% If current priority is better, continue to the next index
continue;
end
else
% Invalid position handling or checking for double logging
duplicateCount = 0;
duplicatePosition = -1;
% Check for duplicate entries in obj.elements
for j = 1:size(obj.elements, 1)
if obj.elements(j, 2) == idx
duplicateCount = duplicateCount + 1;
duplicatePosition = j;
end
end
% If duplicates exist, resolve by comparing priorities
if duplicateCount > 1
currentPriority = obj.elements(currentPosition, 1);
duplicatePriority = obj.elements(duplicatePosition, 1);
if duplicatePriority < currentPriority
% Remove current element with worse priority
obj.elements(currentPosition, :) = [];
obj.positions.remove(idx);
% Adjust positions after removal
for j = currentPosition:size(obj.elements, 1)
obj.positions(obj.elements(j, 2)) = j;
end
else
% Remove duplicate with worse priority
obj.elements(duplicatePosition, :) = [];
obj.positions.remove(idx);
% Adjust positions after removal
for j = duplicatePosition:size(obj.elements, 1)
obj.positions(obj.elements(j, 2)) = j;
end
end
end
end
end
% Step 2: Insert all new elements into the heap
if ~isempty(indices)
% Convert indices and priorities to numeric arrays
indicesNumeric = cell2mat(indices);
prioritiesNumeric = priorities(:);
% Append the new elements to the heap
obj.elements = [obj.elements; [prioritiesNumeric, indicesNumeric]];
% Update positions for the new elements
for i = 1:length(indicesNumeric)
obj.positions(indicesNumeric(i)) = size(obj.elements, 1) - length(indicesNumeric) + i;
end
% Step 3: Perform heapify for all new elements
for i = (size(obj.elements, 1) - length(indicesNumeric) + 1):size(obj.elements, 1)
obj = heapifyUp(obj, i);
end
end
end
function [obj, index, priority] = extractMin(obj)
if isempty(obj.elements)
index = [];
priority = [];
return;
end
% Get the minimum priority and its corresponding index
priority = obj.elements(1, 1); % The minimum priority is always at the top
index = obj.elements(1, 2); % The corresponding index
% Remove the minimum element from the heap
if size(obj.elements, 1) > 1
obj.elements(1, :) = obj.elements(end, :); % Replace the root with the last element
obj.elements(end, :) = []; % Remove the last element
obj = heapifyDown(obj, 1); % Restore the heap property
else
obj.elements = []; % If only one element, clear the heap
end
% Remove the index from the positions map
if isKey(obj.positions, index)
remove(obj.positions, index);
end
[obj, ~] = verifyAndFixMinHeap(obj);
end
%% extractMin multiple indices
function [obj, indices, priority] = extractMinbatch(obj)
if isempty(obj.elements)
indices = [];
priority = [];
return;
end
% Get the minimum priority and its index
minPriority = obj.elements(1, 1);
% Initialize an array to hold indices that are within 10% of minPriority
indices = [];
count = 0; % Counter to stop after 4 elements
% Loop through all elements to find those within 10% of minPriority
for i = 1:size(obj.elements, 1)
if obj.elements(i, 1) <= minPriority * 1.015
indices = [indices; obj.elements(i, 2)]; % Collect indices
count = count + 1;
% Stop after n elements
if count >= 1
break;
end
end
end
% Now, we need to remove the minimum element from the heap
priority = minPriority; % Store the min priority to return
if size(obj.elements, 1) > 1
obj.elements(1, :) = obj.elements(end, :);
obj.elements(end, :) = [];
obj = heapifyDown(obj, 1);
else
obj.elements = [];
end
% Check if the first index exists in the positions map before removing it
if isKey(obj.positions, indices(1))
remove(obj.positions, indices(1));
end
end
function obj = heapifyUp(obj, idx)
while idx > 1
parentIdx = floor(idx / 2);
if obj.elements(idx, 1) < obj.elements(parentIdx, 1)
% Swap the elements and update positions
obj = swap(obj, idx, parentIdx);
idx = parentIdx;
else
break;
end
end
end
function obj = heapifyDown(obj, idx)
leftIdx = 2 * idx;
rightIdx = 2 * idx + 1;
smallestIdx = idx;
if leftIdx <= size(obj.elements, 1) && obj.elements(leftIdx, 1) < obj.elements(smallestIdx, 1)
smallestIdx = leftIdx;
end
if rightIdx <= size(obj.elements, 1) && obj.elements(rightIdx, 1) < obj.elements(smallestIdx, 1)
smallestIdx = rightIdx;
end
if smallestIdx ~= idx
obj = swap(obj, idx, smallestIdx);
obj = heapifyDown(obj, smallestIdx);
end
end
function obj = swap(obj, idx1, idx2)
% Swap elements
temp = obj.elements(idx1, :);
obj.elements(idx1, :) = obj.elements(idx2, :);
obj.elements(idx2, :) = temp;
% Swap positions
tempPos = obj.positions(obj.elements(idx1, 2));
obj.positions(obj.elements(idx1, 2)) = obj.positions(obj.elements(idx2, 2));
obj.positions(obj.elements(idx2, 2)) = tempPos;
end
function [obj, elements] = verifyAndFixMinHeap(obj)
elements = obj.elements;
% Ensure the heap property is valid after heap operations
for i = 1:size(obj.elements, 1)
if i > 1
parentIdx = floor(i / 2);
if obj.elements(i, 1) < obj.elements(parentIdx, 1)
obj = heapifyUp(obj, i);
end
end
end
end
end
end
edit: this is the updated Miniheap to use the dictionary data type instead of the map data type.
classdef MinHeap
properties
elements % Array to store heap elements [priority, index]
positions % Dictionary to store element indices
end
methods
function obj = MinHeap()
obj.elements = [];
obj.positions = dictionary('KeyType', 'double', 'ValueType', 'double');
end
function obj = insert(obj, index, priority)
% Check if the index already exists in the dictionary
if isKey(obj.positions, index)
% Get the current position of the index
currentPosition = str2double(obj.positions(index));
% Ensure the currentPosition is valid
if currentPosition > 0 && currentPosition <= size(obj.elements, 1)
currentPriority = obj.elements(currentPosition, 1); % Get current priority
% Case 1: New priority is better, remove the old element and insert the new one
if priority < currentPriority
% Remove the existing element
obj.elements(currentPosition, :) = [];
remove(obj.positions, index);
% Adjust positions for elements after the removed element
if currentPosition <= size(obj.elements, 1)
for i = currentPosition:size(obj.elements, 1)
obj.positions(obj.elements(i, 2)) = i;
end
end
% Clean up the heap after removal
obj = obj.heapifyDown(currentPosition);
else
% If the current priority is better or the same, no need to insert
return;
end
else
% Case 2: Handle invalid position and potential duplicate log
duplicateCount = 0;
duplicatePosition = -1;
% Check for duplicates in the heap
for i = 1:size(obj.elements, 1)
if obj.elements(i, 2) == index
duplicateCount = duplicateCount + 1;
duplicatePosition = i;
end
end
% Handle duplicate logging
if duplicateCount > 1
currentPriority = obj.elements(currentPosition, 1);
duplicatePriority = obj.elements(duplicatePosition, 1);
% Case 3: If the duplicate has better priority, remove the current element
if duplicatePriority < currentPriority
obj.elements(currentPosition, :) = [];
remove(obj.positions, index);
% Adjust positions after removal
for i = currentPosition:size(obj.elements, 1)
obj.positions(obj.elements(i, 2)) = i;
end
% Clean up after removal
obj = obj.heapifyDown(currentPosition);
else
% Case 4: Otherwise, remove the duplicate
obj.elements(duplicatePosition, :) = [];
remove(obj.positions, index);
% Adjust positions for elements after removal
for i = duplicatePosition:size(obj.elements, 1)
obj.positions(obj.elements(i, 2)) = i;
end
% Clean up after removing duplicate
obj = obj.heapifyDown(duplicatePosition);
end
end
return;
end
end
% Insert the new element at the end of the heap
obj.elements = [obj.elements; priority, index];
obj.positions(index) = size(obj.elements, 1);
% Restore the heap property after insertion
obj = obj.heapifyUp(size(obj.elements, 1));
end
function [obj, index, priority] = extractMin(obj)
if isempty(obj.elements)
index = [];
priority = [];
return;
end
% Extract the minimum element
priority = obj.elements(1, 1);
index = obj.elements(1, 2);
% Replace the root with the last element
if size(obj.elements, 1) > 1
obj.elements(1, :) = obj.elements(end, :);
obj.elements(end, :) = [];
obj = obj.heapifyDown(1);
else
obj.elements = [];
end
% Remove the extracted element from positions
remove(obj.positions, index);
end
function obj = heapifyUp(obj, idx)
while idx > 1
parentIdx = floor(idx / 2);
if obj.elements(idx, 1) < obj.elements(parentIdx, 1)
% Swap elements and update positions
obj = obj.swap(idx, parentIdx);
idx = parentIdx;
else
break;
end
end
end
function obj = heapifyDown(obj, idx)
while true
leftIdx = 2 * idx;
rightIdx = 2 * idx + 1;
smallestIdx = idx;
if leftIdx <= size(obj.elements, 1) && obj.elements(leftIdx, 1) < obj.elements(smallestIdx, 1)
smallestIdx = leftIdx;
end
if rightIdx <= size(obj.elements, 1) && obj.elements(rightIdx, 1) < obj.elements(smallestIdx, 1)
smallestIdx = rightIdx;
end
if smallestIdx ~= idx
obj = obj.swap(idx, smallestIdx);
idx = smallestIdx;
else
break;
end
end
end
function obj = swap(obj, idx1, idx2)
% Swap elements
temp = obj.elements(idx1, :);
obj.elements(idx1, :) = obj.elements(idx2, :);
obj.elements(idx2, :) = temp;
% Swap positions in the dictionary
tempPos = obj.positions(obj.elements(idx1, 2));
obj.positions(obj.elements(idx1, 2)) = obj.positions(obj.elements(idx2, 2));
obj.positions(obj.elements(idx2, 2)) = tempPos;
end
function isEmpty = isEmpty(obj)
isEmpty = isempty(obj.elements);
end
end
end
I've been using matlab for years now for school. all of a sudden, I couldnt seem to start matlab connector on port 31515 which was needed for the app to function. there is nothing running on the port, I opened it in my filewall as I am on windows. I tried deleting and reinstalling it, but when I go to re-install it, I launch the setup file and it crashes after I allow it to make changes to my machine. I looked at the app-data log and I just get this error:
I dont know what to do. I need this for school and There is very little info about this anywhere online. My account is fine, I'm able to login just fine and access it in the browser.
Our MathWorks Usability Team is working on an accessibility project and they want to interview people who use MATLAB and also have experience with screen readers. If you fit the criteria and are interested, sign up here https://www.mathworks.com/products/usability.html?tfa_30=A11Y
Check out our latest release of Onramp courses, which include updated versions of Machine Learning and Deep Learning courses. Onramps are free to all.
Note: Deep Learning courses now use the dlnetwork workflow, such as the trainnet function, which became the preferred method for creating and training deep networks in R2024a. I will check it out personally to learn the new way.
There are also new short courses and learning paths, which require subscription, which may be already included in your license.