I originally made it because I wanted to take the derivative of Ix as a function of time using the `diff()` function. This particular example is simple because each coefficient is a constant, So I can do it manually, but there will be change in the future that I'm not aware of at the moment where these coefficients will become a function of time and there will be many more equations to include.
@PeterCordes You're right, you can interpret the question in that way too. It seems that R2024a and onwards can figure out how many P cores there are. But it still doesn't need to know which cores those are.
I've created an example using the top-left corner of your provided map Click the image to see the full resolution version... I've added displays in yellow so you can see the input map, as well as various values through the model. The input map values I've used are a subset of your example data. You can use a "Prelookup" block for your given RPM (e.g. 1000RPM) to determine the index (zero-based) and fraction (towards the following index) along the RPM axis. You can spoof the pre-lookup for the 2nd axis because we want all values across the gears. To get all indicies we can use 0:(N-1) for N gears, with a fraction [0,0,...,0,1] of the same length (note the final value only is a 1). Feeding this and the table data for torque into an "Interpolation Using Prelookup" block, we can get the entire torque map (interpolated) at the current RPM vs gear. We can now do a 1D lookup of gear number vs torque, which can be done using a "1-D Lookup Table" block. Note that the axis for this block must be monotonically increasing. Your torque map is monotonically decreasing as the gears increase, so we can flip both inputs using a "Selector" block set to indicies N:-1:1 for N gears. You're fortunate here, if your map wasn't monotonically decreasing then this step would be more complicated, because there would be multiple possible gears for your desired torque. I've set the 1-D interp block to "nearest" so you get the closest integer gear choice for your target torque. You could use linear interpolation here if you actually need to know how close to the next gear you are for anything downstream. The main setting I had to change internally for any of the blocks was to set all "source" options for the interpolation blocks to "Input Port" so the data could be specified by the inputs on the left, rather than internal to the block dialog.
You can add a row to your table which is num1 repeated to the same size as num2, then just print the whole table in your format: tbl = [num1*ones(size(num2)); num2; product]; fprintf('%d x %d = %d \n', tbl); Output: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27 3 x 10 = 30 3 x 11 = 33 3 x 12 = 36 Note that the orientation of tbl matters here, the way you had it already works because the placeholders will populate the output string columns-first, since MATLAB is column-major, i.e. the first column is [3; 1; 3] so they are the first three digits used in the printed output 3 x 1 = 3.
If you multiply your matrix through by 3*5/0.005008047876602563 and divide by 256 or 512 then numerical QR codes might at least stand a chance. The matrix values appear to be integers divided by some random number or other (8386501?). ISTR Julia hands numerical matrix work over to LApack so you should get the same answer from that. My instinct is that Matlab is probably getting it wrong but whether or not LAPack/Julia is getting it right I wouldn't like to speculate. Rescaling and round so that the values are all exactly represented ought to help (and also keeping their magnitudes near 1).
Running timed process in background (MATLAB)
@jarhead I've updated my answer with respect to your latest edit
I have been trying to generate the positive ,negative and zero sequence components of the input sinusoid .I have three sinusoidal phases 120 degree separated (Balanced) . The formula to calculate Positive , Negative and zero sequence is given below. where a = 0.5 + i0.866 or 1&lt;120* (complex number). Now if i generate Va , Vb , Vc inside of a matlab itself and use the formulae I get the correct result. Code below and correct result too . % Define Parameters t = 0:0.001:1; % Time vector A = 1; % Amplitude f = 50; % Frequency in Hz % Generate Sinusoidal signals with 120 degrees phase shift v_a = A * exp(1i * (2 * pi * f * t)); % V_a = A * e^(j * 0) v_b = A * exp(1i * (2 * pi * f * t - 2 * pi / 3)); % V_b = A * e^(j * 120°) v_c = A * exp(1i * (2 * pi * f * t + 2 * pi / 3)); % V_c = A * e^(j * -120°) % Call the function to calculate sequence components [va_pos, va_neg, va_zero] = fcn(v_a, v_b, v_c); % Plotting the sequence components figure; % Plot for Positive Sequence Component subplot(3,1,1); plot(t, real(va_pos), 'r', 'DisplayName', 'Real Part'); hold on; title('Positive Sequence Component'); xlim([0 0.3]); ylim([-1 1]); xlabel('Time (s)'); ylabel('Amplitude'); legend show; grid on; % Plot for Negative Sequence Component subplot(3,1,2); plot(t, real(va_neg), 'r', 'DisplayName', 'Real Part'); hold on; %plot(t, imag(va_neg), 'b', 'DisplayName', 'Imaginary Part'); title('Negative Sequence Component'); xlabel('Time (s)'); ylim([-1 1]); ylabel('Amplitude'); legend show; grid on; % Plot for Zero Sequence Component subplot(3,1,3); plot(t, real(va_zero), 'r', 'DisplayName', 'Real Part'); hold on; %plot(t, imag(va_zero), 'b', 'DisplayName', 'Imaginary Part'); title('Zero Sequence Component'); xlabel('Time (s)'); ylim([-1 1]); ylabel('Amplitude'); legend show; grid on; % Function to calculate sequence components function [va_pos, va_neg, va_zero] = fcn(v_a, v_b, v_c) % Define complex exponential for 120 degrees and 240 degrees alpha = complex(-0.5, 0.866); % e^(j*120 degrees) alpha_square = complex(-0.5, -0.866); % e^(j*240 degrees) % Calculate positive sequence component va_pos = (1/3) * (v_a + alpha * v_b + alpha_square * v_c); % Calculate negative sequence component va_neg = (1/3) * (v_a + alpha_square * v_b + alpha * v_c); % Calculate zero sequence component va_zero = (1/3) * (v_a + v_b + v_c); end Now I have Va , Vb , Vc (I generate them now in simulink using sine wave block)and use them as inputs to the simulink function written below (same as one written above). function [va_pos, va_neg, va_zero] = fcn(v_a, v_b, v_c) % Define complex exponential for 120 degrees and 240 degrees alpha = complex(-0.5,0.866); % e^(j*120 degrees) alpha_square = complex(-0.5,-0.866); % e^(j*240 degrees) % Calculate positive sequence component va_pos = (1/3) * (v_a + alpha * v_b + alpha_square * v_c); % Calculate negative sequence component va_neg = (1/3) * (v_a + alpha_square * v_b + alpha * v_c); % Calculate zero sequence component va_zero = (1/3) * (v_a + v_b + v_c); end It gives wrong result as show below .(First plot is Positive sequence , second is negative seq. and third is zero sequence . same as the above mentioned plot). and i suspect it is because it is taking the Va , Vb and Vc in real time (in simulink model). I tried abs() and phase() to extract the phase and magnitude of the sinusoidal wave separately(in real time function in simulink) but to no avail . I would like to know if there is a way of doing extracting a phase and magnitude of a sinosoidal wave in real like in simulink using MATLAB scripting ?
I'm attempting to call a database function that takes a single UUID as a parameter. When I do this: report_id = "5ed30f08-0de0-47f4-99e8-9aeeb8eb2dfe"; query = "select * from public.fn_func($1)"; report_nav = pq_exec_params (conn, query, {report_id}); I get this: __pq_exec_params__: fatal error: ERROR: function public.fn_func(text) does not exist So clearly, something is converting report_id to the PostgreSQL text data type. So I tried to cast to a UUID by changing the query to this: query = "select * public.fn_func($1::uuid)"; But then I get this message: no converter found for element oid 1700 I've definitely added the uuid-ossp module to my database, so I can run this directly against the database: select '5ed30f08-0de0-47f4-99e8-9aeeb8eb2dfe'::uuid; I'm using octave v6.4 to execute the script, running on Ubuntu 22.04 with PostreSQL v14.13.
@jarhead if we take `n` at face value then the peak is at the 2nd index, which according to your `theta` array is approx 0.196rad or 11deg, which does not look like it aligns with the quiver you've drawn. If you let me know how you arrived at that direction maybe I can fill in the gaps...
In MATLAB operators < and > CAN and DO indeed operate matrixes . Try : [1 2 3] > [4 5 6] Result : 1×3 logical array 0 0 0
Nice, we do something similar. Did not realize you need to warnings also after code generation.
There is a task: to simulate waves on the ocean surface 3D case. I faced the problem that when simulating waves in a large area of the ocean (1 km x 1 km), the program takes a very long time to execute. And in fact it is not executed at all. Because during those half an hour of waiting for the result, it was never calculated. Example of my code: clear,clc %% Data x = 0:1:100; % coordinates х [m] y = 0:1:100; % coordinates y [m] g = 9.81; % gravitational constant [m/s^2] speed = 5; % wind velocity [m/s] w0 = (g / speed); % norm.frequency [Hz] dw = 0.1; % frequency step [rad/s] w = 0.8:dw:11.1; % frequency [rad/s] dtt = pi / 18; % angular step [rad] theta = 0:dtt:pi; % direction angles, angles between the wavevector & coordintae axis [rad] %% P-M spectrum, Frequency-Angular spectrum & Amplitude Psi = 8.1e-3 .* ((w/w0).^(-5)) .* exp((-0.74) ./ ((w/w0).^(4))); % P-M spectrum [none] Phi = ((speed)^(5)/g^(3)) * Psi; % self-similar spectrum [s*m^2] Sw = Phi / 2; % frequency spectrum [s*m^2] St = cos(theta).^(4); % angular spectrum [none] Norm = trapz(dtt, St); % norm.coefficient [none] Swt = Sw .* St'; % frequency-angular spectrum [s*m^2] eta0 = sqrt((Swt * dw * dtt) ./ Norm); % amplitude [m] figure(1); subplot(2,1,1) plot(w, Psi); title('$$\Psi$$($$\omega$$) - P-M spectrum', 'Interpreter', 'LaTex'); xlabel('\omega [rad/s]'); ylabel('\Psi [none]'); grid on; subplot(2,1,2) plot(w, Swt); title('$$S(\omega , \theta)$$($$\omega$$) - frequency-angular spectrum', 'Interpreter', 'LaTex'); xlabel('\omega [rad/s]'); ylabel('S(\omega,\theta) [s*m^2]'); grid on; %% Setting the initial phase parameter phase = 2*pi*rand(length(theta),length(w)); %% random initial phase ranging from 0 to 2pi [rad] %% Surface Waving [Linear, 3D (eta & x,y)] at different harmonics & random phase (at one moment in time), different directions of the wavevector (multiple angles) t = 0; % time moment [s] Kabs = (w.^2) / g; % wavevector module [rad/m] Kx = Kabs .* cos(theta)'; % projection of the wavevector onto the x-axis [rad/m] Ky = Kabs .* sin(theta)'; % projection of the wavevector onto the y-axis [rad/m] eta = zeros(length(x),length(y),length(theta),length(w)); % reserving space for calculation results tic for i = 1:length(x) for j = 1:length(y) eta(i,j,:,:) = eta0 .* cos(w * t - Kx .* i - Ky .* j + phase); end end toc % sum(sum(eta,4),3) - double sum of eta over all harmonics (frequencies) and wavevector directions (angles theta), % where '4' и '3' summation indicator for variable frequency and angle etaW = sum(eta,4); etaWA = sum(etaW,3); figure(2) surf(x,y,etaWA); title('\eta(x,y) - surface waving'); xlabel('x [m]'); ylabel('y [m]'); zlabel('\eta [m]'); cbar = colorbar; cbar.Label.String = '\eta [m]'; grid on shading flat One of the code optimization methods that I was able to use is to create an "empty" 4D array (4D array of zeros) eta = zeros(length(x),length(y),length(theta),length(w)); into which, after executing the loop, the calculation results will be filled: eta = zeros(length(x),length(y),length(theta),length(w)); % reserving space for calculation results tic for i = 1:length(x) for j = 1:length(y) eta(i,j,:,:) = eta0 .* cos(w * t - Kx .* i - Ky .* j + phase); end end toc Then I summarize the results by frequency and angle variables: etaW = sum(eta,4); etaWA = sum(etaW,3); Thereby preparing the place for the results in advance. It kind of helped. For example, the code execution time for an area x = 0:1:100; y = 0:1:100; (100 m x 100 m) using this method was 0.7 s (without it, 3.9 s). In the case of an area x = 0:1:500; y = 0:1:500; (500 m x 500 m), the execution time was about 19 seconds (without it...I have no idea, I didn't wait for the code to be executed, but it turns out it was very long). However, with an area x = 0:1:1000; y = 0:1:1000; (1000 m x 1000 m), I have not been getting the desired result for a long time (and it feels like I won't get it at all). Is there any more ways in my case to achieve the desired result and optimize my code so that it can cope with such a scale of data (at the same time, without changing the step in the array)? Note: I have 16 GB of RAM on my computer. My second computer, where I initially performed calculations, hung up completely during the execution of the program, so I had to restart it "manually". So I suppose there is even less RAM in it.
Before trying to solve the issue I'd recommend that you fix the indentation and the variable naming of your code. Looking at the code I have no idea what `a`, `b` and `z` variables are supposed to do. Use descriptive names for your variables. It would also be a good idea that for a smaller range (eg: `for i=1:5`) you provide what is the result you expect, so we can better understand what are you trying to do.
I try to build a restful service using matlab's restFunctionService api, but I get an error when I run it. mySqrt.m： function result = mySqrt(x) result = sqrt(x); end mySqrtService.m serviceL = restFunctionService("EL",["mySqrt"],ClientAccessMode="remote"); matlab version is 2024a. result image Can someone tell me what is going on? I tried reinstalling Matlab, but it didn't solve the problem.
I have the following color scale in an image and I would like to create something similar in a clut file. Here is the scale BlueGreenRedYellow color scale And here is an example of a clut file [FLT] min=0 max=0 [INT] numnodes=5 [BYT] nodeintensity0=1 nodeintensity1=64 nodeintensity2=128 nodeintensity3=191 nodeintensity4=255 [RGBA255] nodergba0=0|0|0|0 nodergba1=0|96|100|64 nodergba2=112|102|0|128 nodergba3=223|106|0|191 nodergba4=255|253|0|255 Do you know how I could do that? It would be great if you have any ideas on how to try to replicate this. I do not know how to approach this issue.
I don't have any code to show, because I do not know what the operation is that I need to perform this task. What operation do I need to use is what I am trying to ask.
Well the problem is I don't know which one will take a short time vs. a long time. But I think what you both said is the way to go. Unless...I can use multiprocessing to both at once and stop both after 2ms.
Using the debugger is a logical approach. But note using coder.extrinsic you can use unsupported MATLAB functions during simulation as well.
Is there an aggregate array function in Matlab? And is it possible to reference different index in such array function?
I'm trying to demodulate a given AM signal in MATLAB, but the results are not satisfactory as you can see: result How can I obtain the demodulated signal (red) correctly? The signal that is modulated and demodulated is xc = Ac * (1 + m * exp(-(t/T0).^2)) .* cos(2 * pi * fc * t); Thanks in advance. Code implemented: Base code: % Parámetros de la señal Ac = 5; % Amplitud de la portadora m = 0.2; % Índice de modulación T0 = 2e-6; % Tiempo constante (2 microsegundos) fc = 30e6; % Frecuencia de la portadora (30 MHz) bw = 15e6; % Ancho de banda del demodulador (15 MHz) fs= 100e6; % Tiempo t = linspace(-5e-6, 5e-6, 1e6); % 1 millón de muestras entre -5 y 5 microsegundos % Señal modulada en AM xc = Ac * (1 + m * exp(-(t/T0).^2)) .* cos(2 * pi * fc * t); %Señal demodulada xd= demod_AM(xc,fc,fs,bw,t); %teórica env_teorica = Ac * (1 + m * exp(-(t/T).^2)); plot(t,xd,t,env_teorica) Function implemented for demodulating the AM signal: function xd=demod_AM(xc,fc,fs,bw,t) % xd = señal demodulada: x_d(t) % xc = señal modulada: x_c(t) % fc = frecuencia de la portadora % fs = frecuencia de muestreo % bw = ancho de banda del filtro % t = vector de tiempos % Mezclar la señal modulada con la portadora (detección coherente) mixed_signal = xc .* cos(2 * pi * fc * t); xd= lowpass(mixed_signal,fs,bw,5); end Lowpass band filter: function newdata = lowpass(data,samprate,cutoff,order) % newdata = lowpass(data,samprate,cutoff,order) % % performs a lowpass filtering of the input data % using an nth order zero phase lag butterworth filter % % given -&gt; data (data) % -&gt; samprate (Hz) % -&gt; cutoff freq (Hz) % -&gt; order of filter (optional: default 2nd order) % % returns -&gt; filtered data if nargin==3 order=2; end; % default to 2nd order % get filter paramters A and B [B,A] = butter(order,cutoff/(samprate/2)); % perform filtering newdata = filtfilt(B,A,data);
You can also set the dbstop options (and see their current state) from the EDITOR tab of the ribbon bar In older versions of MATLAB I believe this was in the dropdown menu under "Breakpoints" instead of "Run"
I still don’t understand what the advantage of 4 separate tests would be if you can’t run them separately.
Is it possible in matlab.unittest.TestCase TestClass to declare property for test methods in such a way, so if it got changed in one test method, following methods use this updated value? In example, if there is such example class: classdef MyTestCase &lt; matlab.unittest.TestCase properties id end Then, i need to set this id property in such a way for all test methods, so i can retain it state across all the test methods, to make every next methods depending on the previous, e.g. % set id = 10 before methods(Test) function testMultiplicationByTwo(testCase) testCase.id = testCase.id * 2; testCase.verifyEqual(testCase.id, 20); end function testIdRemainsUnchanged(testCase) testCase.id = testCase.id + 10; % this testCase.id value should remain 20 after previous case testCase.verifyEqual(testCase.id, 30); end end Tried to do this in methods(TestClasSetup), but looks like it allows only testCase function parameter, so if i set id equals 10 there, it will resets for every new testCase. Any ways to share this updated value across all the test methods? EDIT_1: other possible workaround may be to somehow store the ID after any actions done with it to some external/class-scope variable or parameter and then use it in following tests, e.g. % set id = 10 before methods(Test) function testMultiplicationByTwo(testCase) testCase.id = testCase.id * 2; updated_id = testCase.id % store updated_id somehow for its future use in following tests testCase.verifyEqual(testCase.id, 20); end function testIdRemainsUnchanged(testCase) % provide it here as param (testCase, updated_id) % or load somewhere from external source before test actions, then testCase.id = updated_id + 10; % should be 20 after previous case testCase.verifyEqual(testCase.id, 30); end end Regards, N.
your question appears to be authored with AI assistance. I would not recommend using AI to "shape up" any prose.
I found the answer. this code worked for me clc clear close all f1 = @(t) 3*sin(t); f2 = @(t) 1 + sin(t); syms t T = solve(f2(t) - f1(t)); theta = linspace(T(1), T(2), 300); r1 = f1(theta); r2 = f2(theta); x1 = r1 .* cos(theta); y1 = r1 .* sin(theta); x2 = r2 .* cos(theta); y2 = r2 .* sin(theta); fill([x1, fliplr(x2)], [y1, fliplr(y2)], 'g', 'FaceAlpha', 0.7); hold on t = linspace(0,2*pi, 300); plot(f1(t).*cos(t),f1(t).*sin(t)) plot(f2(t).*cos(t),f2(t).*sin(t)) axis equal
@robert oh, yeah, I didn’t think of the need to restart after setting the Java environment.
It looks like during the fitting process Matlab is trying negative values for b, and that gives a complex result for the logarithm. The error is quite explicit: Complex value computed by model function, fitting cannot continue. Try using or tightening upper and lower bounds on coefficients. To avoid that, as the error suggests, specify a lower value 0 for b. You do that with the 'lower' optional input of the fit function. This forces you to specify lower values for all coefficients, so for ther others use -inf. Added or modified lines are marked with %%: % input x = [4 9 15 25 35 45 55 65 75 85 95 150 250 350 450 900]; y = [335 28 37 9 4 3.5 2 1 0.7 0.6 0.5 0.3 0.1 0.01 0.005 0.001]; % curve fitting ft = fittype('log(a*x^n + b)','independent','x'); ind_b = strcmp(coeffnames(ft), 'b'); %% index of 'b' coefficient lower_values = -inf(1, numel(ind_b)); %% lower value -inf for all coefficients... lower_values(ind_b) = 0; %% ...except 0 for b [fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1 1],... 'lower',lower_values); %% use 'lower' optional input % plots hold on plot(x,y,'o-') plot(x,(fitresult.a .* (x.^fitresult.n)),'-') set(gca, 'XScale', 'log', 'YScale', 'log');
or (2) concatenate the colormaps, and then shift/scale the color data `CData` of the different plot handles to line up with the desired portions of the colormap. A good example (and a link to a Mathworks article about it) can be found in [this answer](https://stackoverflow.com/a/8075772/3460361). (3) Lastly, you could try some helper functions from the file exchange. [`freezeColors`](https://uk.mathworks.com/matlabcentral/fileexchange/7943-freezecolors-unfreezecolors) seems to handle multiple colormap per figure.
levenberg marquardt implementation in matlab problem code no converges
Matlab error solving symbolic systems of equations as functions of time
Digital filter coefficients are the z transform of the analog analog filter transfer function, am I wrong?, I wanted the individual coefficients to implement them in an iterative arduino script that allows for real time filtering with little operations. Part of the issue was how I would apply the coefficients properly, specially since every other coefficient was 0 on the numerator side, I'd need the previous 8th , 6th, 4th and 2nd raw values. Or if it should be the previous 4th, 3rd 2nd and 1st. Or maybe the expression "Z-transform" is used for different topics here?
@confusedcoder please [edit] your question to include details like the required range, and ideally a sketch of the area you expect to be shaded - it's ambiguous which bit you would expect to be shaded over [0,2pi] (since the red circle repeats itself). Can you just treat [pi,2*pi] as independent from [0,pi] and repeat the above code on the 2nd half?
So using simulink, I have a functions set up so they are calculating my required RPM (my x value) based off of how much power I need to pull the plow at the current speed, I also have a function set up to tell me how much wheel torque (my z value) is required to pull the plow at the speed. I do not know how to code it to where I can input my x and z to find y for f(x,y)=z. The top row of the chart is my RPM and the left column is gear, and the value is how much wheel torque is produced with that combination.
Handling Multi-Zone UTM to Lat/Lon/Alt Conversions for Continuous Route Mapping in MATLAB
In Matlab AppDesigner I want to let the user draw a polyline on a plot. After each click I want to print out the point's coordinate on the command line. However I can't get the callback or event listener for the mouse click to work. Only after the user finished the drawpolyline I can access the coordinates. h = drawpolyline('Parent', app.UIAxes,'Color','r'); addlistener(h,'MovingROI',@app.allevents); addlistener(h,'ROIMoved',@app.allevents); addlistener(h,'DrawingStarted',@app.allevents); addlistener(h,'DrawingFinished',@app.allevents); addlistener(h,'AddingWaypoint',@app.allevents); addlistener(h,'WaypointAdded',@app.allevents); addlistener(h,'VertexAdded',@app.allevents); addlistener(h,'DeletingROI',@app.allevents); addlistener(h,'ROIClicked',@app.allevents); addlistener(h,'RemovingWaypoint',@app.allevents); addlistener(h,'WaypointRemoved',@app.allevents); function results = allevents(app,src,evt) evname = evt.EventName; switch(evname) case{'MovingROI'} disp(['ROI moving Previous Position: ' mat2str(evt.PreviousPosition)]); disp(['ROI moving Current Position: ' mat2str(evt.CurrentPosition)]); case{'ROIMoved'} disp(['ROI moved Previous Position: ' mat2str(evt.PreviousPosition)]); disp(['ROI moved Current Position: ' mat2str(evt.CurrentPosition)]); case{'DrawingStarted'} disp('DrawingStarted'); case{'DrawingFinished'} disp('DrawingFinished'); case{'AddingWaypoint'} disp('AddingWaypoint'); case{'WaypointAdded'} disp('WaypointAdded'); case{'VertexAdded'} disp('VertexAdded'); end end With this code I get only the MovingROI and the MovedROI to work. The rest doesn't work. Also it seems that those listeners are only set-up after the object h of the polyline is created. So it wouldn't work anyway to read-out the point's coordinates after each point is clicked. How could I do this? Edit I managed to first create the object app.polyline (formerly h) of the polyline, then set up the listeners and only after that let the user start drawing the line. That way the listeners are already active during the drawing. However, only the following events work: app.polyline = images.roi.Polyline('Parent',app.UIAxes,'Color','r'); addlistener(app.polyline,'MovingROI',@app.allevents); addlistener(app.polyline,'ROIMoved',@app.allevents); addlistener(app.polyline,'DrawingStarted',@app.allevents); addlistener(app.polyline,'DrawingFinished',@app.allevents); addlistener(app.polyline,'AddingVertex',@app.allevents); addlistener(app.polyline,'VertexAdded',@app.allevents); addlistener(app.polyline,'DeletingVertex',@app.allevents); addlistener(app.polyline,'VertexDeleted',@app.allevents); addlistener(app.polyline,'DeletingROI',@app.allevents); addlistener(app.polyline,'ROIClicked',@app.allevents); draw(app.polyline); Of those events, the events 'AddVertex' and 'VertexAdded' only are triggered once the user ads a vertex to an already drawn line. This event doesn't get triggered during a click when the line is first drawn. However I would like to catch the events of those first clicks.
Optimizing two-dimensional interval partitioning for multi-dimensional matrix data
Please provide enough code so others can better understand or reproduce the problem.
I have a matrix containing label values, say identifying grains, states in made-up maps, etc. The values are in range of thousands. The values are unique for homogenoeus region. In case of a map, there is no chance of an exclave etc, but there may be a region with just one neighbour. For example following matrix: [a a a c c d a a b c c d a b b d d d] I would like to visualize the map but no colormap gives reasonable results - some grain pairs have colours almost matching. Is there algorithm to remap the values so there will be no neigbours with a same value but with much lower maximum value? The outcome that looks like some political maps where you have 4 colours that are enough to emphasize the neighbours. For example as follows - [1 1 1 3 3 1 1 1 2 3 3 1 1 2 2 1 1 1] I have tried meddling with colormap trying lines or randomized, but since the "size" of regions waries a lot it does not produce predictable results.
Scipy filter coefficients and filtering in MATLAB
“it seems not possible to create a 4d matrix.” It is possible. And not hard: `cat(4, cell{:})`. But this would be expensive if the matrices are large. It is better to sum the matrices one by one in a loop, then divide by the number of them at the end.
NONE of the decimal values in pv = 0.01:0.01:0.1 can be represented exactly in IEEE double precision. The actual values in pv are approximations to these decimal numbers. You should not expect to get exact decimal results if you do arithmetic with these kinds of double precision values, so you need to adjust your expectations accordingly and modify your code to account for this. This is not weird behavior, it is expected floating point arithmetic behavior in any computer language, not just MATLAB. You might also explore using the linspace( ) function instead of the colon operator.
Possible duplicate of https://stackoverflow.com/questions/32913301/matlab-date-string-results-in-java-lang-string-in-python-scipy-io, which said that the simplest way to do this is to export the dates as strings and grab them back with usual Python `datetime.datetime` methods. TimeStamps are a date format only used by Matlab, according to https://stackoverflow.com/questions/48542674/how-to-read-matlab-datetimes-stored-in-a-file-using-scipy-io-loadmat
Trying to implement compressed sensing with FFT in Matlab. I have implementet compressed sensing for time series with descret cosine transform sucsessfully, but changing dct to fft and idct to ifft is not enough since the code give me only zeros. %% Generate signal, DCT of signal n = 4000; % points in high resolution signal t = linspace(0, 4000, n); x = 0.5*cos(2* 0.008 * pi * t) + 0.5*cos(2* 0.016 * pi * t) + 0.5*cos(2* 0.064 * pi * t) + 0.5*cos(2* 0.256 * pi * t); xt = fft(x); % Fourier transformed signal PSD = abs(real(xt)).^2/((n-1)*1); % Power spectral density %% Randomly sample signal p = 128; % num. random samples, p=n/32 perm = round(rand(p, 1) * n); y = x(perm); % compressed measurement %% Solve compressed sensing problem Psi = dct(eye(n, n)); % build Psi Theta = Psi(perm, :); % Measure rows of Psi %s = cosamp(Theta,y',10,1.e-10,10); % CS via matching pursuit %% L1-Minimization using CVX cvx_begin; variable s(n); minimize( norm(s,1) ); subject to Theta*s == y'; cvx_end; xrecon = idct(s); % reconstruct full signal The code work fine with DCT but give zeros when changing basis to FFT. Any idea of how to implement FFT here?
I can set it to "Dual Simplex" using `options.Algorithm = "dual-simplex"`but this produces the same result is there a way to set it to Highs? I'm aware i can use use max iterations and i might have to but max time would be an ideal
One way to obtain those three wrong subplots is if (in your correct code) your input data has only the real component, that is, if your replace `exp(1i *` by `sin(`, or just take `real` of `v_a`, `v_b`, `v_c`; can you verify that you have generated the complex sinusoidal signal?
I would like to create a color scale the matches an image
@LuisMendo You are right, that is my bad
Thanks for the solution @CrisLuengo . It works, even though I don't understand what ```cell{:}``` does. When I stored it in a variable like ```cells=cell{:}``` and I print its size ```size(cells)```, I obtain the size of just one 3d matrix...
I’m working on a project where I convert geographic coordinates (latitude, longitude, altitude) to UTM coordinates (zone, east, north, altitude) for calculating azimuth and elevation. However, I’m facing a significant challenge because my map spans multiple UTM zones, and as points cross these zone boundaries, the UTM coordinates become inconsistent. This creates discontinuities when I try to map a continuous route, especially for longer paths that cover large geographic areas. My workflow involves: 1. Converting lat, lon, alt to UTM (east, north, zone, altitude). 2. Performing calculations in UTM coordinates for azimuth and elevation. 3. Converting the results back to lat, lon, alt to visualize and analyze the path. The primary issue is handling points across different UTM zones without causing jumps in coordinates due to zone changes. I’ve tried different methods but can’t achieve smooth transitions between zones. I’d appreciate any advice on managing multi-zone UTM conversions in MATLAB, especially if anyone has experience with similar mapping projects or the MATLAB Mapping Toolbox. To handle azimuth and elevation calculations accurately for my project, I convert geographic coordinates (latitude, longitude, altitude) to UTM coordinates. The calculations work well within a single UTM zone, but I encounter issues when my points cross zone boundaries. Specifically, the east and north values can change significantly at the boundary, causing discontinuities in what should be a smooth route. My goal is to visualize a continuous path on a map, regardless of zone changes, but the abrupt shifts in UTM coordinates make this difficult. I try to direct Lat/Lon Calculations: I attempted to bypass the issue by performing calculations directly on latitude/longitude coordinates instead of UTM. While this avoids zone boundary issues, my azimuth and elevation calculations are less accurate because UTM-based calculations were designed to be more precise for short-distance measurements. % List of geographic coordinates (lat, lon) that cross at least two UTM zones latitudes = [40.0, 40.5, 41.0, 41.5, 42.0]; longitudes = [-75.0, -74.5, -74.0, -73.5, -73.0]; % Initialize arrays for UTM coordinates and UTM zone names utmZones = cell(size(latitudes)); eastings = zeros(size(latitudes)); northings = zeros(size(latitudes)); % Convert geographic coordinates to UTM for i = 1:length(latitudes) [eastings(i), northings(i), utmZones{i}] = deg2utm(latitudes(i), longitudes(i)); end % Display UTM coordinates and their respective zones disp('UTM Coordinates and Zones:'); disp(table(latitudes', longitudes', eastings', northings', utmZones')); % Plot UTM coordinates with color-coding for different UTM zones figure; hold on; % Define colors for different zones for better visual distinction colors = lines(numel(unique(utmZones))); for i = 1:length(latitudes) zoneIndex = find(strcmp(utmZones, utmZones{i})); scatter(eastings(i), northings(i), 100, 'filled', 'MarkerFaceColor', colors(zoneIndex, :), 'DisplayName', utmZones{i}); end title('UTM Coordinates Across Multiple Zones'); xlabel('Easting (m)'); ylabel('Northing (m)'); grid on; legend('show'); hold off; % Convert UTM back to geographic coordinates latitudes_back = zeros(size(latitudes)); longitudes_back = zeros(size(longitudes)); for i = 1:length(eastings) [latitudes_back(i), longitudes_back(i)] = utm2deg(eastings(i), northings(i), utmZones{i}); end % Display converted geographic coordinates disp('Converted Back to Geographic Coordinates:'); disp(table(latitudes', longitudes', latitudes_back', longitudes_back')); % Visualize the original and converted back coordinates on a map figure; hold on; scatter(longitudes, latitudes, 100, 'filled', 'r', 'DisplayName', 'Original Coordinates'); scatter(longitudes_back, latitudes_back, 100, 'filled', 'b', 'DisplayName', 'Converted Back Coordinates'); title('Comparison of Original and Converted Back Coordinates'); xlabel('Longitude'); ylabel('Latitude'); legend; grid on; hold off;
Matlab: Stop execution of one line but continue program execution
This is matlab, right? You should tag it.
I have an STL file and I would like to make a binary mask from it in MATLAB, that would be defined similar to this: stl_mask = zeros(size(stl_file)); stl_mask(stl_indices) = 1 I have searched around and there is a stlread function that lets me visualize the STL file in MATLAB, but I am a bit lost on how to work around it. This is the STL file that I'm using. For the moment, I have just this small code to visualize the STL file: clearvars filename = 'example.STL'; [v, f, n, c, stltitle] = stlread(filename); figure; patch('Faces',f,'Vertices',v,'FaceVertexCData',c);
Welcome to Stack Overflow! Can you please [edit] your post to show the, non-working, code you wrote for the DSSS and include the error message in the post? We cannot help you to debug code you haven't shown us, see [mre].
Use the debugger. Set a breakpoint in your callback function, then you can see what is going on inside it. https://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html
How do I access a MATLAB UI function in another .m file?
From the [documentation](https://uk.mathworks.com/help/optim/ug/linprog.html#buusznx-options) it looks like the `MaxTime` option only applies if you're using a _Dual-Simplex Algorithm_ (Highs or Legacy). Did you try with one of those set? Otherwise you could approximate how long each iteration is taking and use `MaxIterations` instead, which is applicable to all algos
It can be the case that k_1 ~= k_2. It just happens to not be true for the example I gave. In general I have to assume k_1~= k_2.
Seems like you're doing some sort of combination of two distinct things: Use a simple function, which can be in its own .m file or one of the methods of your main class: % in your initialise class constructor you still have buttonCreate(app); % In buttonCreate.m function buttonCreate(app) % Create file load 1 app.fileload1 = uibutton(app.gridLayout, 'push'); app.fileload1.FontSize = 36; app.fileload1.Layout.Row = [8 9]; % ... end Use a class to hold references to all of your buttons, in which case the objects you create would be properties of that class, rather than the main app object: % in your initialise class constructor you create a buttons % object and assign it to the buttons property. % The buttons don't need to know anything about the app, just % the target grid layout to parent the buttons app.buttons = buttons( app.gridLayout ); % In buttons.m classdef buttons &lt; handle properties fileload1 end methods function obj = buttons( grid ) % Create file load 1 obj.fileload1 = uibutton(grid, 'push'); obj.fileload1.FontSize = 36; obj.fileload1.Layout.Row = [8 9]; % ... end end end
You are just missing 3rd parameter for printing. And use for loop for simplicity. Please check the below code. for k=1:length(num2) fprintf ('%2.0f x %2.0f = %3.0f \n',num1, table(1,k),table(2,k)); end
fmincon Biasing one ouput and minimizing the objective Function
How to pass matrix as input to matlab function from .net app?
Your matrix A is singular. The MATLAB doc states that in these cases, mldivide is unreliable ("... When working with ill-conditioned matrices, an unreliable solution can result ...") and suggests to use lsqminnorm( ) or pinv( ) instead (see "Tips"). E.g., >> A = [ -1 0 0; 1 1 -1; 0 -1 1 ]; >> B = [-1; 0; 1]; >> A\B Warning: Matrix is singular to working precision. ans = NaN NaN NaN >> A*ans-B ans = NaN NaN NaN >> lsqminnorm(A,B) ans = 1.0000 -0.5000 0.5000 >> A*ans-B ans = 1.0e-15 * 0.4441 -0.3331 -0.1110 >> pinv(A)*B ans = 1.0000 -0.5000 0.5000 >> A*ans-B ans = 1.0e-15 * 0.2220 -0.4441 0.2220
I implemented a first draft of the Adams-Bashforth multistep-solver in C++. To make this method work, you need coefficients. In Wikipedia these are the bj in this formula: y_n+1 = y_n + h * sum_over_j(bj * f(t_n-j, y_n-j)) I couldn't find any tables online that go beyond order 6 for these coefficients, so I tried calculating them myself with this Matlab script: function bj = adamsBashforthCoefficients(order) h = 1; nodes = -(0:(order-1)); bj = zeros(1, order); for j = 1:order L = @(x) arrayfun(@(xi) prod((xi - nodes([1:j-1, j+1:end])) ./ (nodes(j) - nodes([1:j-1, j+1:end]))), x); % bj(j) = integral(L, 0, 1) / h; bj(j) = integral(L, 0, 1, 'AbsTol', 1e-12, 'RelTol', 1e-12) / h; % Test if tolerances were to high - they weren't end end Up to order 6 this gives the same values as found online, so I assumed they are correct. However: Up to order 6 Adams-Bashforth seems to work fine, but order 7 or higher give frequent instabilities. Meaning: Some variables explode to huge values. Can higher orders in Adams-Bashforth create instabilities where lower orders work? Should that already happen at order 7 (Matlabs ode113 goes up to order 11 or 12)? Or do I simply have the wrong coefficients? If the coefficients are wrong, I would greatly appreciate it, if somebody could show me code how to calculate them correctly or simply point me to a table that goes to higher orders (at least 11-12). For comparison: Here is, what my script calculated for orders 6-8: // Order 6 { 2.970138888888889, -5.502083333333333, 6.931944444444445, -5.068055555555556, 1.997916666666667, -0.329861111111111 } // Order 7 { 3.285730820105820, -7.395634920634921, 11.665823412698412, -11.379894179894180, 6.731795634920635, -2.223412698412698, 0.315591931216931 } // Order 8 { 3.589955357142857, -9.525206679894177, 18.054538690476193, -22.027752976190477, 17.379654431216931, -8.612127976190475, 2.445163690476190, -0.304224537037037 }
@Argyll Noted it. I hope I understood the flaws of my question correctly and made the right corrections to it for a better understanding of what is happening in my code for a better understanding of the problem.
I want to calculate the eigenvalues of the (discrete) Laplace operator in 3D. For this I want to use the matlab command eigs. I have implemented the Laplace operator as a function as it is recommended in the documentation of eigs. For this it is necessary to design the function, such that it takes one array (1D) as an input and gives one array (1D) as an output. Please note, that I know, that the spectrum of the (discrete) Laplacian is known analytically. My actual problem goes beyond and I tried to minimize my actual issue to the question you read in this post. In other words: I would like to use the function together with eigs in any case. Here I define my function: function Lap = Laplace(f,Lx,Ly,Lz,Nx,Ny,Nz); kx(1:Nx/2)=(0:Nx/2-1)*2*pi/Lx; %Calculate the momentum vector in x-direction kx(Nx/2+1:Nx)=(-Nx/2:-1)*2*pi/Lx; ky(1:Ny/2)=(0:Ny/2-1)*2*pi/Ly; %Calculate the momentum vector in y-direction ky(Ny/2+1:Ny)=(-Ny/2:-1)*2*pi/Ly; kz(1:Nz/2)=(0:Nz/2-1)*2*pi/Lz; %Calculate the momentum vector in z-direction kz(Nz/2+1:Nz)=(-Nz/2:-1)*2*pi/Lz; [Kx,Ky,Kz]=meshgrid(kx,ky,kz); %Calculate a grid in the k-space K=sqrt(Kx.*Kx+Ky.*Ky+Kz.*Kz); %Calculate at every grid-point the absolute value of the k-vector f3D = reshape(f,[Nx,Ny,Nz]); %reshape the input vector in order to multiply grid-point by grid point with K Lap3D = ifftn(K.*K.*fftn(f3D)); %Action of the Laplacian Lap = Lap3D(:); %Reshape back to 1D-format end And then I run the command: Lx=1; %length in x-direction Ly=1; %length in y-direction Lz=1; %length in z-direction Nx=128; %number of points in x-direction Ny=128; %number of points in y-direction Nz=128; %number of points in z-direction Afun= @(x) Laplace(x,Lx,Ly,Lz,Nx,Ny,Nz); tic eigs(Afun,Nx*Ny*Nz,12,'smallestabs','Tolerance',1e-9 ,'Display',1,'SubspaceDimension',100) toc As I result I should get the 12 smallest eigenvalues, but when I run the code it produces the following output: 1.0e-05 * 0.206138475834832 0.208291225315224 0.208291225315224 0.208291225315224 0.208291225315225 0.210454435947029 0.210454435947030 0.210454435947030 0.210489412585876 0.210489412585876 0.210489412585877 0.212627347524422 This result seems wrong. It looks like the eigenvalues are shifted. I do not see my mistake. Thanks for any kind of help.
@beaker Unfortunatelly the "data" are not in the form of a graph-representing matrix. On the other hand, naming the problem behind helps a lot.
Thanks @LuisMendo and AnderBiguri I don't have symbolic toolbox license and finally used [Mutiprecision Computing Toolbox](https://www.advanpix.com/) do to the test (NB: It is no free after trial but extremely fast and solve my precision issue in recurrence). Regarding link digits/bits correspondance, looking at how [floating points](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) encoding the relation is `digits = (bits - bitsReserverExponent)*log10(2)` , so almost 34 digits for quadrule-precision (128bits)
You can use the linear indices returned by unique to give you the column number of each unique integer. Since the integers are given in sorted order by default, the list of indices (converted to column numbers) gives one column of the output. Given: A=[ 1 10 9 1 2 4 3 2 11 3 12 5 6 13 4 6 7 15 8 7 5 8 14 16] Find the indices of the first occurrence of each integer: [Y,I] = unique(A); % Y is not necessary, only there for verification disp([Y,I]); 1 1 2 10 3 3 4 18 5 20 6 5 7 14 8 7 9 17 10 9 11 19 12 12 13 13 14 16 15 22 16 24 (Note that if we were not guaranteed to have each integer appear at least once, we could use Y as a row index into the result array.) The linear indices can then be converted to (row and) column numbers using ind2sub: [~,C] = ind2sub(size(A),I) C = 1 2 1 3 3 1 2 1 3 2 3 2 2 2 3 3 If both occurrences of an integer are guaranteed to be in the same column, we're done: Q = [C, C]; If occurrences of an integer can be in different columns, we'll just use unique a second time: B = A; B(4,[2,3]) = B(4,[3,2]) B = 1 10 9 1 2 4 3 2 11 3 5 12 <-- 12 and 5 swapped 6 13 4 6 7 15 8 7 5 8 14 16 [~,I] = unique(B, "first"); [~,C] = ind2sub(size(B),I); Q(:,1) = C; [~,I] = unique(B, "last"); [~,C] = ind2sub(size(B),I); Q(:,2) = C; disp(Q); 1 1 2 2 1 1 3 3 2 3 <-- 5's are in different columns 1 1 2 2 1 1 3 3 2 2 3 3 3 3 <-- 12 is only in 1 column 2 2 2 2 3 3 3 3
@LutzLehmann Indeed: Further tests revealed, that it depends on the step-size wether or not orders above 6 are stable. At a bit smaller step-sizes higher orders were stable, so my coefficients are correct I think. Do you think it makes sense to use Adams-Moulton (with the next timestep estimated by Adams-Bashforth) to increase stability? My ODE-function is very expensive, so the usual 2 evaluations with Adams-Bashforth-Moulton are inefficient (compared to one eval with Adams-Bashforth). But I also could just interpolate y_(n+1) at first. Do you think, this would be precise enough?
You’re computing `condition = (pres-1)*3 + stimulus`. Just write a loop to set those values.
I have a recursive computation code of mine (containing only simple +, *, exp, etc arithmetic on complex valuated numbers) that starts to loose precision when increasing the depth of iterations and I was willing to see if using quadruple-precision (or higher) numbers would help. For this I was willing to try following toolboxes: HPF MPT But I'm a bit confused about how to use them because precision is to be provided as a number of digits after comma and I don't see from examples how this relates to quantities being stored/manipulated as 64/128 bits values. Can you show me some quick example to create quadruple-precision (i.e. 128 bits) with those toolboxes and explain relation with precision as number of digits as expected as argument in those toolboxes ?
I have a 1x12 cell in Matlab and each element of this cell has a 3d matrix. I want to make the mean of these 3d matrices, so that I obtain a 3d matrix that has the same dimensions of each one of the 3d matrices of the cell and that is the mean of the 12 3d matrices. How can I do this operation ? I tried to extract each cell and create a 4d matrix so that I could do mean(fourdmatrix,4) . However, it seems not possible to create a 4d matrix. Ideed, a code like this: cell={threedmatrixA, threedmatrixB, ...} fourdmatrix=[]; for i=1:12 fourdmatrix(i)=cell{i}; end does not work. How can I do it ?
By the way, Argyll didn’t complain about not understanding the code, he complained that it is not *mimimal*. There’s a lot of redundant stuff happening in the code that is not necessary to understand the problem. This in turn makes things harder to understand, we have to do more work to read and understand all of that code and look for the relevant bits. You should always try to make code as concise as possible for the purpose of asking others for help with it. Minimal, but complete, so that we can copy-paste and run it ourselves. Please read the text at the link Argyll posted.
Hey Cris, Thanks for your reply ! I really like your second idea, I'll try this out. Maybe another possibility could be to create my own subclass of the python list or tuple, which is transparent to method calls (transmitts unknown method calls to the list or tuple's elements' instances like in Matlab). I could achiege this using a decorator of some sort, and use that one instead of the default python list or tuple in my code... Like you said, there are many variants. Thanks again !
Difference in Cholesky Decomposition Results Between Julia and MATLAB
The error in me not being able to recreate the waveforms like in those subplots was that i was only adding the real part of the complex sinosuidal waveform . In order for me to extract the waveform I used "PLL block" (to get the frequency 'f') and clock (to get the time values) . Then the code goes as follows. function [va_pos,vb_pos,vc_pos,va_neg,vb_neg, vc_neg, va_zero,vb_zero,vc_zero,va_reconstructed,vb_reconstructed,vc_reconstructed] = fcn(t, f, va_in, vb_in, vc_in) % Calculate the phase-shifted voltages v_a = va_in * exp(1i * (2 * pi * f * t)); % V_a = A * e^(j * 0) v_b = vb_in * exp(1i * (2 * pi * f * t - 2 * pi / 3)); % V_b = A * e^(j * 120°) v_c = vc_in * exp(1i * (2 * pi * f * t + 2 * pi / 3)); % V_c = A * e^(j * -120°) % Define complex exponential for 120 degrees and 240 degrees alpha = exp(1i * 2 * pi / 3); % e^(j * 120 degrees) alpha_square = exp(-1i * 2 * pi / 3); % e^(j * 240 degrees) % Calculate positive sequence component (full complex value) va_pos = (1/3) * (v_a + alpha * v_b + alpha_square * v_c); vb_pos = alpha_square * va_pos; vc_pos = alpha * va_pos; % Calculate negative sequence component (full complex value) va_neg = (1/3) * (v_a + alpha_square * v_b + alpha * v_c); vb_neg = alpha * va_neg; vc_neg = alpha_square * va_neg; % Calculate zero sequence component (real part) va_zero = (1/3) * (v_a + v_b + v_c); vb_zero = va_zero; vc_zero = va_zero; % Reconstruct the original signal (optional) % This can be done to check if va_in ≈ va_pos + va_neg + va_zero va_reconstructed = va_pos + va_neg + va_zero; vb_reconstructed = vb_pos + vb_neg + vb_zero; vc_reconstructed = vc_pos + vc_neg + vc_zero; end Now after you reconstruct . For plotting the real time values you can plot using real() in time domain. I was plotting using real and then reconstrucing using the real part as well (That was the error) . Thank you for the help .
Start with a smaller matrix, see what kind of differences you see. Look at the numeric values, you'll be able to answer your question of "Could this be due to numerical precision differences?".
Environment: Matlab R2022b Simulink model Problem: I was generating code from Embedded coder and generated codes have header file declaration present in the C file instead of H file. I used the same model in another computer with R2020b (after exporting to previous version), and same model generated the # includes in H file.
I think you're looking for "graph coloring", but unfortunately I see no built-in implementation in MATLAB. I did find an implementation in File Exchange, but I haven't used it and don't know how good it is.
I have created a script in Matlab that processes several data channels into figures and produces a Word doc and PDF filled with the figures pasted into it. This produces a fairly large word document with several different sections. I am using the Word COM through the actxserver function to create this document. In it I set up a table of contents using the following 4 lines: rang = word.ActiveDocument.Range(0, 0); word.ActiveDocument.TablesOfContents.Add(rang); word.ActiveDocument.TablesOfContents.Format = 0; word.ActiveDocument.TablesOfContents.Item(1).Update; This produces a suitable table of contents, however, I also want this table of contents to act as internal hyperlinks to there respective sections. I have spent quite a while on this and have found several possible methods that didn't work. Has anyone tried to do something like this before and managed to get the hyperlinks working in the generated Word Doc and (if possible in the PDF saved from the Word Doc. Any help will be appreciated word.ActiveDocument.TablesOfContents.UseHyperlinks = true; I expected this to work because as far as I can find this is the documented command.
Fast computation of 2D-convolution using "kernel" in fourier space
Incrementing an extra step in MATLAB loop yields incorrect values?
function cikti = sigmoidDerivative(x) cikti = sigmoid(x) .* (1 - sigmoid(x)); This code part has to be changed to function cikti = sigmoidDerivative(x) cikti = x .* (1 - x); because in the Jacobean function, the "sigmodiDerivative()" funtion is called with parameter that already calculated with sigmoid() function [~ , jA1] = forward_pass(jinput_vals(i),W1,b1,W2,b2); derivW1 = -1 * W2'.* sigmoidDerivative(jA1) *jinput_vals(i); "jA1" is already return from the "sigmoid()" function and so repeated unnecessary sudden increase and decrease of lamba problem solved.
@Irreducible Hello, thank you very much for the comment. How would you load them directly onto matlab? I tried using thos SOS structure but it's just the same array? I'll check out the fvtool, thank you very much again.
There is a group of excel files (10 files), in each of which there is a table: 2 columns (the name of the parameter, its value) and 12 rows (the number of parameters and, accordingly, their values). It is necessary to calculate the average between 10 variations of a single parameter. There is a program for this below. However, I noticed that he performs the calculation with an error of one ten-thousandth of a number, he underestimates it. For example, here's what the result gives me: Matlab Averaging using Excel 0.0288 0,02891568 0.0008 0,000836121 0.0012 0,00117159 0.0723 0,07248086 0.0858 0,085798107 0.0867 0,086977032 0.1030 0,102957729 0.9524 0,959947104 -0.0050 -0,005002288 0.0008 0,000837283 -0.0000 -1,28168E-05 0.0000 2,17761E-06 clc, clear; % Folder with Excel files folder = 'The path to the folder with 10 excel files'; % the path to the folder files = dir(fullfile(folder, '*.xlsx')); % we get a list of all excel files % Initialize the vector to store the average values average_values = []; % Loop through all files for i = 1:length(files) % The full path to the file file_path = fullfile(folder, files(i).name); % Reading data from an Excel file opts = detectImportOptions(file_path, 'VariableNamingRule', 'preserve'); data = readtable(file_path, opts); % Check if there is at least one numeric column if any(varfun(@isnumeric, data, 'OutputFormat', 'uniform')) % We extract only numeric data numeric_data = data{:, varfun(@isnumeric, data, 'OutputFormat', 'uniform')}; % We calculate the average values for the rows, ignoring NaN avg_values_per_row = mean(numeric_data, 2, 'omitnan'); % Saving the average values in an array average_values = avg_values_per_row; else warning('There are no numeric columns in the "%s" file.', files(i).name); end end % Displaying average values disp('Average values by line:'); disp(average_values); % Displaying the number of rows disp('Number of lines:'); disp(length(average_values)); As you can see, for parameters number 1, 4, 6, 8, the underestimation goes from 0.0001 to 0.0007 units (in the case of the 8th parameter, the underestimation is already in one thousandth of the number). What is most interesting is that if you manually enter 10 values of each parameter into the mean function in Matlab and calculate, it will give the correct result without this underestimation (using the example of the 8th parameter): >> mean([0.952380002 0.980380905 0.97087088 0.95237715 0.952379051 0.970871364 0.980383351 0.925921306 0.961536062 0.952370972 ]) ans = 0.9599 Where can there be a problem in the code and how to fix it so that it gives an accurate result? (the attachment contains a folder with files from the example: https://drive.google.com/file/d/1COPpBq2mU8Ww62DRvbOKTtr_aC-LsCIL/view?usp=sharing)
I want to plot a semi-random graph in Matlab
How to implement attenuation into a Bluetooth Mesh MATLAB script?
I would require wrapping the logic of my Simulink model to be obfuscated or hidden. One of the ways to perform it is to create a similar s-function block with the object code generated from the same Simulink block. I am facing difficulty in realizing this programmatically. Is there a way around to realize them programmatically or rely on GUI to create manually.
Right, but the entire point of chaos theory is that you can say mathematically whatever you want, in practice you will never be able to simulate it. At some point you need a tolerance of 1e-(e^100000000000)), so its meaningless to try to do it. Note that the same question can be applied to any differential equation, but _some_ differential equations will give you the same answer I gave you, while others are easily solvable numerically. I don't know if its knowable how to scale the tolerances (which is why I didn't answer the question) but even if its possible, it would be at least exponential.
there's a matlab function called estimatetrf, if i'm not mistaken
I want to numerically evaluate the following integral: If the function f is given in discrete form on a grid, I want to be able to very efficiently compute the integral. The idea is to understand it as a multiplication in the Fourier space and use FFT: if xi and eta are the Fourier variables. I tried to implement this in Matlab, but dont get exact results (probably because I dont quite understand the FFT). I have the following minimal working example in Matlab: N = 101; x = linspace(-1, 1, N); hx = x(2)-x(1); [X, Y] = meshgrid(x, x); a = 1/2; f = 2/pi*a*real(sqrt(1-(X.^2+Y.^2)/a^2)); f_pad = zeros(2*N, 2*N); f_pad(1:N, 1:N) = f; k = linspace(0, pi/hx, N+1); k = [k k(end-1:-1:2)]; hk = k(3)-k(2); [KX, KY] = meshgrid(k, k); K = sqrt(KX.^2 + KY.^2); chess = mod((1:2*N)+(1:2*N)',2); chess = -chess; chess(chess==0) = 1; G = 1./K; G(1,1) = 4*integral2(@(x,y) 1./(sqrt(x.^2+y.^2)),0,0.5*hk,0,0.5*hk)/hk^2; R = ifft2(G.*2.*chess.*fft2(f_pad), 'symmetric'); R = R(N+1:end, N+1:end); Rana = (a^2-x.^2/2) .* (abs(x)&lt;=a) + ... real(a^2/pi*((2-x.^2/a^2).*asin(a./abs(x))+sqrt(x.^2-a^2)/a)) .* (abs(x)&gt;a); plot(Rana); hold on; plot(R((N-1)/2+1,:)); R is the result of the integral, f is the input function and G is the fraction in the Fourier-space; the singularity at xi = 0 and eta = 0 of G is dealt with by taking the average value of the function in the surroundings of the point. I compare the final result to an analytical solution, which in this case exists. But it doesn't match perfectly (and doesn't get better, when I increase N? Why is that? And I also don't understand why the chess-matrix is necessary (I copied it from an example I found)?
Matlab has object arrays, Python has lists or tuples. Calling a method of a class on an object array of objects of that class, is easy in Matlab: A = [Class1(1), Class1(2)]; B = A.toClass2(); see "Invoking Methods on an Object Array" here In Python, this would not be 1 to 1 transferable because on the second line, the interpreter would look for the method toClass2() in the List class, which it will not find (->error). I found out that this can be solved from outside that method's definition, on the user side, by calling it in a for loop, list comprehension, map of a function or lambda function, or even using numpy.vectorize(), see this. Each of these solutions imply heavier syntax on the user side, and one thing still misses; what if I want the method Class1.toClass2() can decide for itself how to treat a list of multiple objects received as input. For instance a method Class1.Sum() would logically sum all elements on which it is applied and return a single object, whereas another doing some transformation like Class1.toClass2() might as well return an array of new objects. Alternatively, one can make the method toClass2() also accept a List as self input, and call it explicitly on the second line on the list A using: B = Class1.toClass2(A) This allows methods choosing how to treat List inputs, but generates slightly heavier syntax on the user's side. Does anyone see another solution ? Maybe there is one using method decorators, class decorators, or even subclassing the List class .. Else more generally, how to adapt this OOP software architecture design thinking from Matlab arrays to Python's universe ?
N = 101; x = linspace(-1, 1, N); hx = x(2)-x(1); y = linspace(-1, 1, N); hy = y(2)-y(1); [X, Y] = meshgrid(x, x); a = 1/2; F1 = 2/pi*a*real(sqrt(1-(X.^2+Y.^2)/a^2)); % f(x,y) this is f(x,y) with a=.5 figure(1) hs=surf(X,Y,F1) hs.EdgeColor='none'; And f1 is the integrant, the actual function to integrate 2D f1 = @(x_,y_) 2/pi*a*real(sqrt(1-(x_.^2+y_.^2)/a^2)) Setting x=.5;y=.5; as parameters. x0=.5;y0=.5; F2=@(x1,y1) f1(x1,y1)./((x0-x1).^2+(y0-y1).^2).^.5; Z=integral2(F2,x(1),x(end),y(1),y(end)); resulting in Warning: Reached the maximum number of function evaluations (10000). The result fails the global error test. &gt; In integral2Calc&gt;integral2t (line 129) In integral2Calc (line 9) In integral2 (line 105) In double_integral_example (line 23) Warning: Reached the limit on the maximum number of intervals in use. Approximate bound on error is 1.6e-15. The integral may not exist, or it may be difficult to approximate numerically to the requested accuracy. &gt; In integralCalc/iterateScalarValued (line 372) In integralCalc/vadapt (line 132) In integralCalc (line 75) In integral2Calc&gt;@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions) (line 17) In integral2Calc&gt;@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x)) (line 17) In integralCalc/iterateScalarValued (line 323) In integralCalc/vadapt (line 132) In integralCalc (line 75) In integral2Calc&gt;integral2i (line 20) In integral2Calc (line 7) In integral2 (line 105) In double_integral_example (line 26) Warning: The integration was unsuccessful. &gt; In integral2 (line 108) In double_integral_example (line 26) function integral2 needs some fields changed from default to return a result Z=integral2(F2,x(1),x(end),y(1),y(end),'Method','iterated','AbsTol',0,'RelTol',1e-10) Z = NaN too strict Z=integral2(F2,x(1),x(end),y(1),y(end),'Method','iterated','AbsTol',1e-5,'RelTol',1e-8) Z = 0.250008992645364 Now it works I am submitting the above lines as answer while one of my machines is busy calculating the following F3=zeros(N,N); for k1=1:1:numel(x) for k2=1:1:numel(y) x0=x(k1);y0=y(k2); F2=@(x1,y1) f1(x1,y1)./((x0-x1).^2+(y0-y1).^2).^.5; F3(k1,k2)=integral2(F2,x(1),x(end),y(1),y(end),'Method','iterated','AbsTol',1e-5,'RelTol',1e-8); end end figure(2) hs3=surf(X,Y,F3) The narrow gap is again MATLAB getting results but error out of specs. Comment: Double loop on integral2 is not time efficient for N&gt;10 , at least for the machine I used to answer this question. There are other ways to get a result for large N but since understand that would be another question, on how to optimize an already working solution to the above question.
This is what the FFT computes: https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Definition — it uses k=0..N-1 as frequencies. But you can assign frequencies however you want, it’s just about how you interpret the maths. Note how the DFT does not consider a sampling frequency, it just has N input samples and produces N output frequencies. There is no specific values associated to the X axis (sample locations) of either input or output.
In MATLAB - We explicitly defining the number of segments through the window size and overlap. spectrogram(x, windowSize, overlap, nfft, Fs, 'yaxis'); While in python - the number of segments is determined by the length of the input signal and the NFFT parameter By keeping this as reference...we need to adjust the input signal length and the NFFT parameter. Fs = 50 * 10**6 N = 500 desired_segments = 500 and f, t, Sxx = signal.spectrogram(x, fs=Fs, nperseg=N, noverlap=0, nfft=N, return_onesided=False, scaling='density') Final code import numpy as np import matplotlib.pyplot as plt from scipy import signal Fs = 50 * 10**6 N = 500 desired_segments = 500 t = np.linspace(0, 1, Fs, endpoint=False) x = np.sin(2*np.pi*1e6*t) + 0.5*np.sin(2*np.pi*2e6*t) signal_length = N * desired_segments if len(x) > signal_length: x = x[:signal_length] else: x = np.pad(x, (0, signal_length - len(x)), mode='constant') f, t, Sxx = signal.spectrogram(x, fs=Fs, nperseg=N, noverlap=0, nfft=N, return_onesided=False, scaling='density') Sxx = np.fft.fftshift(Sxx, axes=0) f = np.fft.fftshift(f) plt.figure(figsize=(10, 8)) plt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.title('Spectrogram') plt.colorbar(label='Power/Frequency [dB/Hz]') plt.show() Output You can check shape like so print(f"Shape of the spectrogram matrix: {Sxx.shape}") Output: Shape of the spectrogram matrix: (500, 500)
I use mcc -m main.m to create an exe file. When I run it on another computer that does not have Matlab installed, I get this error Could not find version 24.1 of the MATLAB Runtime. Attempting to load mclmcrrt24_1.dll. Please install the correct version of the MATLAB Runtime. Contact your vendor if you do not have an installer for the MATLAB Runtime. I asked GPT, and it suggested I use mcc -m main.m -R -logfile But it doesn't work. I want the exe file to run on a computer that did not have Matlab installed or MATLAB Runtime. How can I do that?
If you need implicit methods, then the extrapolation will be lacking whatever method you use, as the solution is too curvy. The stability regions for the implicit methods are larger, but also finite and shrinking for higher orders. I'm not sure if I remember this right, but the comparison in terms of function evaluations between comparable Runge-Kutta and multi-step is rather tight. And using Newton-like methods is always better than the simple fixed-point iteration.
Thanks but this does not correspond to the data I presented.
Some people want to think of the (radial) frequencies being in the range -π/2 to π/2 even. That depends on interpretation. But the actual algorithm uses frequencies k=0..N-1, given samples at n=0..N-1. If you explain a bit more what you really want to accomplish, we might be able to help you. Right now I’m not certain about what you need.
The DFT is defined mathematically that way. So the question is why it is defined that way in maths. To me, it does feel more natural that the exponents in the imaginary exponentials increase from 0 to _N_ − 1 (see [here](https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Definition)). Also, with your proposal the cases for _N_ odd or even need to be treated differently, as in the latter case there is no center frequency. The expressions for the start and end indices in the sum that defines the DFT would be more cumbersome
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Hmm, after `jenv /path/to/jdk`, I see three files in `$HOME/.matlab/R2023a` which have changed, namely `matlab.mlsettings`, `history.m`, and `toolbox_cache-9.14.0-2485697813-glnxa64.xml`. Now `history.m` is just the history file and `toolbox_cache-9.14.0-2485697813-glnxa64.xml` appears to be lists of files for each toolbox. The other one `matlab.mlsettings` might contain configuration data, but it is binary data, so I can't readily edit it to put in the path I need.
What do you mean "the results get stuck at the bus"? Can you [edit] your question so that we might be able to diagnose it without downloading and running that model ourselves?
Hence if I do runopf and it returns infeasible, it cannot obtain an opf with the given branch limits (and equally for runpf with the given generator settings), correct? I am still a little confused, bc I still get violations on the branches when running opf and MATPOWER returns "feasible". Also, when running opf, one generator changes its values (always exactly one, which is weird)? Also, by "running opf with tight generator limits" you mean that I should set Pmax and Pmin to similar values than my desired pg, correct? I still end up with the same gen changes. Is there something I oversaw?
How to enforce MATPOWERs runpf to keep the flow limits?
There is nothing pertaining to the Z-transform in this post.
If the question is about "how MATLAB maximize it's performance with the knowledge of a hybrid structured CPU", then part 1 helps with it: Disclaimer: All credits goes to the MathWorks Support Team, I just copy and pasted it from here. Parallel Computing Toolbox can use both types of cores. MATLAB will rely on the operating system to schedule processes across the available cores, whether they are performance-oriented or designed for efficiency. However, it's important to note that while PCT can utilize both performance (P) and efficiency (E) cores, the best practice for computational tasks is to start with a number of parallel workers equivalent to the number of physical P cores. This is because P cores are akin to traditional physical cores in terms of computational capability, while E cores are optimized for power-saving and less intensive tasks. From R2024a onwards Parallel Computing Toolbox's local 'Processes' profile will use a number of default workers equal to the number of P cores on the machine. This can be altered by the same steps in the link at the bottom. Windows Power Plan If you are using Windows, you may wish to look at adjusting your Windows Power Plan. If this is set to ‘balanced’ then Windows may deprioritise background or unselected applications so they will only run on the E cores of the system. Setting the power plan to ‘High Performance’ should cause the Intel Thread Director to be able to select which workloads are best suited to each core. Performance Expectations You may still see performance gains when including efficiency cores in your parallel computations, but the scaling may differ from performance cores. The actual performance improvement will depend on the nature of your code and the specific tasks being executed. In some cases, efficiency cores can handle less demanding parallel tasks effectively, allowing the performance cores to focus on more intensive computations. If you wish to change the default number of cores used: See also this Answer for further details on changing the number of cores leveraged by Parallel Computing Toolbox: https://www.mathworks.com/matlabcentral/answers/2042101-how-can-i-increase-the-number-of-matlab-workers-inside-parallel-computing-toolbox-to-use-all-the-cor Part 2. If the question is really about "How MATLAB estimate the exact number of P-cores and E-cores on a given system" Then it is very hard to tell because MATLAB is a closed source software package that targets multiple OS and hardware platforms, and they constantly make changes under the hood without notifications. One speculative method might be the "GetSystemCpuSetInformation" function on Windows, which returns a _SYSTEM_CPU_SET_INFORMATION type of structure: typedef struct _SYSTEM_CPU_SET_INFORMATION { DWORD Size; CPU_SET_INFORMATION_TYPE Type; union { struct { DWORD Id; WORD Group; BYTE LogicalProcessorIndex; BYTE CoreIndex; BYTE LastLevelCacheIndex; BYTE NumaNodeIndex; BYTE EfficiencyClass; union { BYTE AllFlags; struct { BYTE Parked : 1; BYTE Allocated : 1; BYTE AllocatedToTargetProcess : 1; BYTE RealTime : 1; BYTE ReservedFlags : 4; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME2; union { DWORD Reserved; BYTE SchedulingClass; }; DWORD64 AllocationTag; } CpuSet; } DUMMYUNIONNAME; } SYSTEM_CPU_SET_INFORMATION, *PSYSTEM_CPU_SET_INFORMATION; where the EfficiencyClass field could provide related information. However this is not a definitive answer and there might never be one.
performing x[:signal_length] will result in having a 5ms instead of 1 sec spectrogram which is not the case with Matlab. 500x500 should represent 50Mhz band and 1 sec duration spectrogram
I am attempting to create a MATLAB app programmatically to have it be more organized. As such I have split up code into different files based on what it does, I have one file to initialize the buttons on the screen. When I attempt to build a function callback for a button I seem to successfully build it. No errors are shown in the terminal, however I get an audible Windows Error noise and the callback action is not triggered. Here is my code: function obj = selectLoad( grid ) %Create file load 1 obj.fileLoad1 = uibutton(grid, 'push'); obj.fileLoad1.FontSize = 36; obj.fileLoad1.Layout.Row = [8 9]; obj.fileLoad1.Layout.Column = 1; obj.fileLoad1.Text = 'Load 1'; obj.fileLoad1.ButtonPushedFcn = {@fileLoad1Callback}; end function fileLoad1Callback(src, event) fileLoad1.Text = 'Ice Cream'; end grid here is an argument I pass from my main initilization file that has the uigridlayout for the entire app. No error code is present so it is very difficult for me diagnose the issue.
Please attach the Excel input file, or a portion of such file. Readers should be able to reproduce the question. Without the Excel file you describe in the question, or part of it, there's no way to reproduce your question.
OK, so in the 1000x1000 case the array is indeed huge. >15 GB in memory. You cannot do that. So I'll repeat what I deleted from my earlier comment when I was confused about the size of the arrays: either don't compute the full 4D array, or if you really need to do so, then compute it and write it out in sections so that you don't need to keep the whole thing in memory at once.
Where (in what file and directory) is the path to the Java JDK stored in Matlab?
I am trying to create a MATLAB code that takes input and output signals from an Excel file. In the first column of the file, there is the time at which the data was acquired, in the second column are the amplitude response data. In the third column, there are the time instants of the input, and in the fourth column, the amplitudes provided as input. Since the output data is generated by another software, there are fewer output data points than input data points. My goal, as stated in the subject, is to create a MATLAB code that can generate a Bode plot to find the resonance frequency. I have tried using spline interpolation to increase the number of output points, and then I perform the FFT on both to find the gain. Additionally, I have tried using the MATLAB function pwelch, but I did not obtain acceptable results in terms of noise and peaks. I think I might be doing something wrong. Below is my code. I expect a resonance frequency between 140 and 250 Hz, and I expect there not to be all that noise. clear close all clc %% Excel files = dir('*.xlsx'); t0 = 2; figure; for i = 1:length(files) x_out = []; x_in = []; t_out = []; t_in = []; raw = readtable(files(i).name); %% Definition of Input t = linspace(0, 0.36, 1024); freq = str2num(extractBefore(files(i).name, '.xlsx')); t_in = t; x_in = sin(freq * 2 * pi * t); x_in = spline(t_in, x_in, t); %% Definition of Output t_out = raw{:, 1} - t0; % From 0-0.36s x_out = raw{:, 4}; t_out = t_out(~isnan(t_out)); x_out = x_out(~isnan(t_out)) / 9810; %Conversion from mm to units of gravity %% Interpolation x_out_interp = spline(t_out, x_out, t_in); %% Pwelch window = hanning(256); noverlap = round(length(window) * 0.66); % 66% overlap Fs_in = 1 / (mean(diff(t_in))); Fs_out = 1 / (mean(diff(t_out))); [pxx_in, f_in] = pwelch(x_in, window, noverlap, [], Fs_in); [pxx_out, f_out] = pwelch(x_out_interp, window, noverlap, [], Fs_out); %% Plot PSDs figure(2) subplot(2, 1, 1) hold on plot(f_in, 10 * log10(pxx_in), DisplayName=files(i).name) title('Power Spectral Density of Input Signal') xlabel('Frequency [Hz]') ylabel('Power/Frequency [dB/Hz]') grid on legend("show") subplot(2, 1, 2) hold on plot(f_out, 10 * log10(pxx_out), DisplayName=files(i).name) title('Power Spectral Density of Interpolated Output Signal') xlabel('Frequency [Hz]') ylabel('Power/Frequency [dB/Hz]') grid on legend("show") %% Gain gain = 10 * log10(abs(pxx_out) ./ abs(pxx_in)); %% Plot Bode figure(3) hold on semilogx(f_in, gain, DisplayName=files(i).name) title('Bode Plot - Gain') xlabel('Frequency [Hz]') ylabel('Gain [dB]') grid on xlim([0 1000]) legend("show") end Input: Output: The input can also be generated in MATLAB without being extracted from an Excel file, as long as it has an amplitude of 1 and a frequency of 140 Hz. The time duration is equal to 0.36s Excel file open In this Excel file, the results derived from the FEM analysis are contained (1st column: time [s], 2nd column: amplitude, which should be divided by 9810 to convert it into gravity units), and it is configured as the output for the Bode diagram. The sinusoidal input for plotting the Bode diagram is generated by the MATLAB code.
Note that the FFT computes a discrete Fourier transform, not a continuous-domain Fourier transform. They are not the same thing, even though the former can be used to approximate the latter. The DFT is periodic, both in the input and the output. You need to take this into account. You also need to take sampling theory into account.
Of course there will be rounding errors that will/can result in wildly different results. But the point of numerical simulations is to get as close to the truth as possible. Mathematically (so with infinite precision and time steps) I think it should be possible to shrink a system and get a perfect analogous system. One chooses the error tolerances so that the result is reasonably correct with reasonable runtime. My question is: How do relTol and absTol scale with the system. That has nothing to do with chaos and the same question could be applied to any differential equation...
How to create 3D surface with different layers that each have their own colormap in matlab?
You can't. Not unless you have a Matlab coder license and generate C code from which you can actually compile a stand alone executable. You can redistribute the Matlab runtime with your current application: https://www.mathworks.com/products/compiler/matlab-runtime.html. Check the licenses to make sure they fit your use case.
An exact method to systematically compute the coefficients using algebraic means was presented in my answer in https://math.stackexchange.com/questions/3473300/please-correct-if-there-a-mistake-on-my-explicit-formula-of-7th-steps-adam-bashf. Check the literature for specifics, in short, you will find that the stability region for these methods shrinks very rapidly. The consequence is that the usable step-sizes may reach the boundaries of the floating-point format, the increasing number of steps giving a corresponding increase in the amplitude of the floating-point noise.
Is it possible to stop with a breakpoint at error OR warning during Matlab run with dbstop?
@RobertDodier I poked around a bit, the binary file is a ZIP file. I've updated the answer.
I added a sentence in my question, but is it true that the algorithm uses frequencies k=0...N-1? From the definition it looks like [0, 2pi/N,..., 2Pi*(N-1)/N].
I’m working on a MATLAB project that requires FFT and IFFT computations on large images using GPUs. Currently, the image size is 32000×25600 with double precision data. Although we need to process even larger images, we’ve reduced the size due to GPU memory constraints. We’re using two NVIDIA GeForce RTX 3080 GPUs (each with 9.51 GB of available memory) to accelerate the process. Below is a simplified version of our code: **parpool('Processes', 2); object = ones(32000, 25600, 'gpuArray'); objectFT = fftshift(fft2(object));** However, this approach runs into GPU memory issues. I attempted to split the image into smaller chunks to manage memory better and wrote a function to divide the computation across two GPUs using spmd as shown below: **function result = dualGPUFFT(image, chunkSize, inverse) [m, n] = size(image); result = zeros(m, n); spmd gpuDevice(labindex); disp(['Worker ', num2str(labindex), ' using GPU ', num2str(gpuDevice().Index)]); if labindex == 1 localData = gpuArray(image(1:floor(m / 2), :)); % Top half else localData = gpuArray(image(floor(m / 2) + 1:end, :)); % Bottom half end localResult = gpuArray.zeros(size(localData), 'like', localData); numChunks = ceil(size(localData, 1) / chunkSize); for chunkIdx = 1:numChunks rowStart = (chunkIdx - 1) * chunkSize + 1; rowEnd = min(chunkIdx * chunkSize, size(localData, 1)); chunk = localData(rowStart:rowEnd, :); if inverse chunkResult = ifft2(ifftshift(chunk)); else chunkResult = fftshift(fft2(chunk)); end localResult(rowStart:rowEnd, :) = chunkResult; end resultLocal = gather(localResult); if labindex == 1 result(1:floor(m / 2), :) = resultLocal; else result(floor(m / 2) + 1:end, :) = resultLocal; end end end** Unfortunately, this approach also failed to handle the memory issue effectively. Here are my key questions: How can I efficiently manage GPU memory for FFT/IFFT computations on such large images? Are there other chunking strategies or libraries that could handle this better in MATLAB? Does performing FFT/IFFT on GPUs for large images generally offer significant speed improvements over CPUs? I’d greatly appreciate any insights, recommendations, or alternative approaches for handling such large-scale FFT/IFFT computations.
Also, I'm not sure whether the beautiful symmetry between direct and inverse DFT (just a change of sign in the exponent and a multiplying constant) would be maintained with your suggested definition
Your loop just returns values from the last workbook. Open 'Param10.xlsx' and compare values with averages you displayed in the question. The error is here: for i = 1:length(files) ... average_values = avg_values_per_row; ... end On every loop run average_values gets current values. As I wrote before, you need to sum something like this (don't know the exact syntax): average_values = sum(average_values,numeric_data) and after the loop divide each element of average_values by 'length(files)'.
How can I create an FIR from difference of two impulse responses?
Oh, right, thank you! The code seems to work now, so I guess the next step is for me to figure out how to save the "out" variable in the nifti format - instead of passing more character array around (EDIT: it worked with "niftiwrite")
I have 2 data sets in Matlab, each one is a 2xn array of data, where the top row contains timestamps. However, not each timestamp has a data point. Now I want to compare these datapoints, but I cannot use the index without filtering any data points that are not mutual. So to give an example: A = [ 1, 2, 3, 5, 6; 3, 4, 5, 7, 8 ] B = [ 1, 2, 4, 5, 6; 9, 8, 6, 5, 4 ] I want to use some kind of operation or set of operations to end up with A = [1, 2, 5, 6; 3, 4, 7, 8 ] B = [ 1, 2, 5, 6; 9, 8, 5, 4 ] So that the times and datapoints match the indexes. I have used ismember to identify the indexes that are not mutual, but I'm having trouble deleting the offending columns from the original set. I multiplied the ismember output with the dataset, but all it does is set the timestamps in the columns to zero.
I want to pass matrix as input from .net app to matlab function Matlab function: function myfunc(info); sort(info) end I want info input be recieved in function like this: info = [... 0 0 0; ... 0 120 0; ... 240 120 0; ... 240 0 0; ... ]; and .net code: MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(@"cd C:\scripts\myfunc.m"); object result = null; int[,] input = new int[4, 3] { { 0, 0, 0 }, { 0, 120, 0 }, { 240, 120, 0 }, { 240, 0, 0 } }; matlab.Feval("myfunc", 0, out result, input); This gives me error in Feval line--> "error using norm first argument must be single or double." And when I change input to be like this int[,,] input = new int[4, 1, 3] { { {0, 0, 0} }, { {0, 120, 0} }, { {240, 120, 0} }, { {240, 0, 0} } }; It gives another error --> 'index in position 1 exceeds array bounds. index must not exceed 1 How to solve this?
I'm encountering some very weird behaviour in some MATLAB code I've written, and can't quite tell why. If I increment the loop from 0.01 in steps of 0.01 to 0.09, all values are correct. However, if I step from 0.01:0.10, a single extra step, MOST values are correct but some previous ones get absolutely messed up. The weird thing is that the loop doesn't depend on any previous values, each iteration is 'fresh' so I'm kind of perplexed why this is happening. Any idea? I should also note that if I run the problem values independently out of the loop, the correct answer is obtained. MWE under images... MWE: v = [0.5]; pv = 0.01:0.01:0.1; %broken version.. n = 1000; h = 3.841; fp = zeros(size(pv)); % Preallocate to avoid size issues for kx = 1:length(pv) p = pv(kx); % Recalculate functions dependent on 'p' a = @(y) y; b = @(x) x; c = @(x, y) p*n - y; d = @(x) n*(1 - p) - x; new = @(x, y) (n.*(a(y).*d(x) - b(x).*c(x, y)).^2) ./ ... ((a(y) + b(x)) .* (c(x, y) + d(x)) .* (a(y) + c(x, y)) .* (b(x) + d(x))) - h; for j = 1:length(v) yp = 0:p*n; xp = v(j).*n - yp; f = new(xp,yp); fin = find(f&lt;0); yv{j} = yp(fin); end % Use ndgrid dynamically for all cell elements grid_cells = cell(1, numel(yv)); [grid_cells{:}] = ndgrid(yv{:}); % Convert grid into combinations matrix combinations = cell2mat(cellfun(@(x) x(:), grid_cells, 'UniformOutput', false)); % Check that each element in the row is less than or equal to the next valid_rows = all(diff(combinations, 1, 2) &gt;= 0, 2); % Keep only valid combinations filtered_combinations = combinations(valid_rows, :); i = 1; probs = zeros(size(filtered_combinations)); probs(:,1) = hygepdf(filtered_combinations(:,1),n,round(n.*p),round(v(1).*n)); while i &lt; (length(v)) remy = round(n.*p - filtered_combinations(:,i)); yhits = filtered_combinations(:,i+1) - filtered_combinations(:,i); npick = round(n.*(v(i+1) - v(i))); nrem = round(n.*(1-v(i))); probs(:,i+1) = hygepdf(yhits,nrem,remy,npick); i = i +1; end full = prod(probs,2); falsepositive = 1 - sum(full) % Store results in 'fp' array fp(kx) = falsepositive; % Explicitly reset variables if needed (avoiding clearvars) end
What are the values of `[rows,cols,slices]` after that first line?
Just out of curiosity, which test framework allows for this? I don’t know many, but the few I do know do not allow for inter-dependent test cases. I guess you could fudge something with global variables, but how are you going to force the four tests being run in the right order? I honestly think that your four steps are part of a single test.
How to properly include the DC component in a MATLAB log-log plot for spectral analysis?
Confused with matlab arbitrary precision toolboxes
The FFT is an algorithm that computes a DFT, not a continuous-domain FT. The periodicity is N, the length of the signal. In a discrete world it makes no sense to have a periodicity of 2π, since that is not an integer number.
The Code Rm = corr(timeModel, 'Type', 'Spearman'); Rm %First row of Rm contains the correlation coefficients between the values of avgExcTime and the expected execution times for all the possible values of KEY3:0 Rc = Rm(1,2:17); %The entry of Rc with the highest positive value corresponds to the guessed %key (the first entry of Rc is 1 and corresponds to the autocorrelation of %avgExcTime, therefore is discarded) [corr,idx] = max(Rc); guessedKeyNibble = idx-1``` The error Index in position 1 is invalid. Array indices must be positive integers or logical values. Error in Part3 (line 60) Rm = corr(timeModel, 'Type', 'Spearman'); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^``` What can fix this? The TimeModel has a size of 16 x 17 which is correct and I am really lost as to what is going wrong here?
If someone had a real-world problem that depended on E-core detection, support might answer with details. Otherwise some reverse-engineering might shed some light, for example `strace` on Linux or an equivalent tool on Windows can trace what system-calls a process makes. But that would only tell us if a Windows version of MATLAB calls `GetSystemCpuSetInformation` at all, not whether it checks the `EfficiencyClass` field in the output. Interesting that such a field exists at all; the docs mention ARM bit.LITTLE which predates Alder Lake's implementation of the same idea by several years.
I have found one error. Mistakenly, I forget to set the parameterVector with the new weight just before the second call of the jacobian function. But the model still can't converge. I checked input and output values with ready made function in MatLab. It works with no problem. There is still convergence problem but this time error function not increasing but stuck around 1.
Why can't you save the state, do the method that takes 1ms and if it doesn't get the right answer then and only then use the slower method. Otherwise you have to add something in the iterative code loop to give up after N seconds of wall clock time. IOW "this line of code" needs to have a way of returning a timeout error to your program.
I have the following system of differential equations that arose form circuit analysis where the following simplification was made. Simplification of equations The systems of equations is as follows: System of Equations I created 2 MATLAB files, the first where I define each I_x as a symbolic variable and a second file where I define each I_x as a function of time I_x(t). When I try to find I_4 as a function of time in file 2. I get an error error: structure has no member 'I4' error: called from Gauging_Circuit at line 12 column 1 Below are the tests I preformed: % File 1 syms I1 I2 I3 I4 R1 R2 R3 C1 C2 C3 Vi; eqn1 = Vi == I1*((1/C1) + R1) + I2*(-(1/C1)) + I3*(0) + I4*(0); eqn2 = Vi == I1*(-(1/C1)) + I2*((1/C1)+(1/C2)+(1/C3)) + I3*(0) + I4*(0); eqn3 = Vi == I1*(0) + I2*(-(1/C3)) + I3*((1/C3) + R3) + I4*(0); eqn4 = Vi == I1*(0) + I2*(-(1/C2)) + I3*(0) + I4*((1/C2)+R2); % Try lin solve, If it doesnt work, Try solve function below %[A, B, C, D] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [I1, I2, I3, I4]); %X = linsolve(A,B); sol = solve([eqn1, eqn2, eqn3, eqn4], [I1, I2, I3, I4]); disp(sol.I4) File 1 output: Output From file 1 Screenshot When I try to make each current a function of time I_x(t) I get an error. Below is the code and output from file 2. % File 2 syms I1(t) I2(t) I3(t) I4(t) R1 R2 R3 C1 C2 C3 Vi(t); eqn1 = Vi == I1(t)*((1/C1) + R1) + I2(t)*(-(1/C1)) + I3(t)*(0) + I4(t)*(0); eqn2 = Vi == I1(t)*(-(1/C1)) + I2(t)*((1/C1)+(1/C2)+(1/C3)) + I3(t)*(0) + I4(t)*(0); eqn3 = Vi == I1(t)*(0) + I2(t)*(-(1/C3)) + I3(t)*((1/C3) + R3) + I4(t)*(0); eqn4 = Vi == I1(t)*(0) + I2(t)*(-(1/C2)) + I3(t)*(0) + I4(t)*((1/C2)+R2); % Try lin solve, If it doesnt work, Try solve function below %[A, B, C, D] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [I1, I2, I3, I4]); %X = linsolve(A,B); sol = solve([eqn1, eqn2, eqn3, eqn4], [I1(t), I2(t), I3(t), I4(t)]); disp(sol.I4) File 2 Output (Actual name is "Gauging_Circuit"): error: structure has no member 'I4' error: called from Gauging_Circuit at line 12 column 1 Why am I getting this error? When I change both files so that line 12 disp(sol.I4) becomes disp(sol), I get the exact same outputs but addressing I4 gives me an error in the second file.
My data is Matlab Datetime datatype NOT a 1x1 java.lang.String.
I don't think you can do that. I think you need to rewrite the first bit of code to be aware of how long it's running, and have it return an error value (or error out) if it's taking too long. I assume that bit of code has a loop, in the loop you can check how long it's been running and just `error` if it's too long. The calling code can `try`/`catch` and run the second bit of code in the `catch` part.
Thank you Cris and Wolfie. Now it's working: sample=[-1,-1,-1,1.5,2,2.5]; z=0; for i=1:100 outcome(i)=randsample(sample,1)*(2^z); if outcome(i)>0 z=0; else z=z+1; end; end;
MATLAB - Coloring the area bounded by two curves in polar coordinate system
But when I look at the documentation of fft (https://se.mathworks.com/help/matlab/ref/fft.html), it looks like we use frequencies in the range [0, 2pi/N,..., 2Pi*(N-1)/N]. My question is, can one use the frequencies [0, L/N,..., L*(N-1)/N]?
Optimization and acceleration of large-scale calculations in the process of wave simulation
this doesn't work because `theta` must be between 0 and 2*pi and when you modify the first line to achieve that, it colors the whole area inside of `r2` instead of the area between `r1` and `r2`. is there a way to use the `fill` function to accomplish this?
Why are you using a cell anyway? They're best suited for non-numeric or non-uniform data... You probably want to define a numeric array `sample=[-1,1.5,2,2.5];` with square brackets
Filtering data by matching values in Matlab
You want a 2D output array, don’t compute the full 4D array and then project it. Instead, compute the projection in your loop. The intermediate 4D array in the case of a 1000x1000 output is more than 15 GB, which means your 16 GB system cannot hold it in memory in its entirety (since MATLAB and the OS also need some space), and will swap out portions to disk. If the loop were to index the array as eta(:,:,i,j) then it wouldn’t be so bad, as you’re writing to a contiguous part of memory. But since you index eta(i,j,:,:), every loop iteration is writing to bytes all across the 15 GB memory block. Thus, every loop iteration has your system read from disk and write back to disk most the array. This obviously slows down things a lot, and is called “thrashing”, because in the days of spinning hard disks, this made a lot of noise. In general, when writing loops, you should always consider the order that array elements have in memory, and loop such that you access array elements in memory order as much as possible. This optimizes the usage of the system’s cache. In MATLAB, arrays are stored with the elements along the 1st dimension contiguous in memory. So you don’t want the first dimension index being the outer loop, and you don’t want to access elements along the last dimension(s) as a single block. To project inside the loop, instead of eta = zeros(length(x),length(y),length(theta),length(w)); for i = 1:length(x) for j = 1:length(y) eta(i,j,:,:) = eta0 .* cos(w * t - Kx .* i - Ky .* j + phase); end end etaW = sum(eta,4); etaWA = sum(etaW,3); write etaWA = zeros(length(x),length(y)); for j = 1:length(y) for i = 1:length(x) etaWA(i,j) = sum(eta0 .* cos(w * t - Kx .* i - Ky .* j + phase), 'all'); end end Note how I not only added the sum over all dimensions inside the loop instead of at the end. I also swapped the loop order, so that the inner loop goes over the first dimension. This is the most efficient way to loop in MATLAB. By the way, “reserving space for calculation results” is crucial. This is called pre-allocation in MATLAB speak, and avoids the huge amount of work done when enlarging an array repeatedly.
@beaker given that OP's context is weeks in a month, there always will be. I've handled the edge-case already that the list ends too soon, the only other edge case is that the list starts mid-month which could also be handled. I've expanded my example to show how it could be done in a loop for more robustness though
I am not clear as to what you want to accomplish. Could you include example input and output data?
What makes you say the results _seem wrong_? What are your expected outputs?
The Fourier Transform and its inverse is linear. That means that `x-y = ifft(fft(x) - fft(y)`. So I am not sure what the idea is here.
Our sample set is given as {-1,1.5,2,2.5}. b = from "outcome" value to outcome(index100) value. There is a problem that outcome(1) cannot be equal to a matrix value. Hence I set "outcome" (without (1)index) equal to the matrix value. But unfortunately, yet > or < operators cannot work with a matrix value, And I don't know how to work with rand function. In fact, I like when a negative value is randomly chosen then the next time double of it being selected, but when a positive random value is chosen it don't get doubled. I give you the code: sample={-1,1.5,2,2.5}; for i=1:100 z=i; outcome=randsample(sample,1); if outcome>0 z=1; else z=i; outcome(z)=(2^z)*outcome; end; if i==1 result=outcome; end; end; b = outcome:outcome(100); result = sum(b,"all"); plot result; end Any vision for helping me?
The variables that my model needs are mostly structures: say, struct1, struct2, etc.. The model then accesses their fields as inputs to different masks. Whether using parsim or parfor/sim, I need to run an initialization scripts with different inputs to the script and this main script also calls a bunch of subroutines. A non-parallel workflow is as follows: Change input parameters: param1, param2, etc. Execute the main initialization script (calling other scripts) Modified structures: struct1, struct2, etc. are available in the Workspace Run the model Repeat Steps 1 through 4 with another set of values for param1, param2, etc. I tried to use set_param to assign the fields of the structures to the masks inside a parfor first to put together a simin before executing parsim, but it seems to hate executing the main initialization script before I can even use them for set_param. I tried using parsim, but basically the same approach. Thus, it fails in a similar manner. How do I convert the non-parallel workflow listed above to a parallel computing scheme?
Welcome to SO! Without a code snippet to help diagnose, you are just asking the community to do your work for you. Please include what you have tried, with enough code to allow others to reproduce the problem. For help with this, read https://stackoverflow.com/help/minimal-reproducible-example .
At the bottom of the documentation page I linked, there's a section titled "See Also"... That may be helpful.
I just got it to work, thank you so much!
You should avoid using `table` as a variable name, since you're shadowing the [in-built function `table`](https://uk.mathworks.com/help/matlab/ref/table.html)
You just give both commands, one after the other, to stop at either condition. Each sets a breakpoint condition. You can have many, many different breakpoint conditions set up at the same time. That is why there's a `dbclear all` command.
I'm trying to draw a bodeplot of a discrete contorl system with the "ss" and "bodeplot" function: % X(k+1) = AX(k)+Bu(k) % y(k) = CX(k)+Du(k) sys_d = ss(m_A, m_B, m_C, m_D, Ts); h1 = bodeplot(sys_d); It turned out that the result is not as expected in low-frequency domain (s close to 0, z close to 1), and I further check of value of transfer fucntion at z=1 by directly calculating C*(zI-A)^{-1}B=C(I-A)^{-1}*B: transfunc = m_C*inv(eye(size(m_A))-m_A)*m_B; And there is a warning "Matrix is close to singular or badly scaled. Results may be inaccurate." So it seems that the matrix is ill-conditioned when z is close to 1, and the bodeplot function itself is not accurate. How can I solve this problem? Thanks very much! I've also tryed methods like using function "evalfr" to calculate the gains at many frequency points, and the results are the same.
Matlab fittype of a logged power law, with a y-intercept
It looks like you've encountered a naming conflict with MATLAB's built-in corr function. Here's what's happening and how you can fix it: The Issue You likely executed a line similar to: [corr, idx] = max(Rc); By assigning the output to a variable named corr, you shadow MATLAB's built-in corr function. As a result, any subsequent calls to corr(...) are interpreted as attempts to index into your variable corr rather than calling the function. How to Fix It Clear the Conflicting Variable Remove the corr variable from your workspace to restore access to the built-in function: clear corr Use a Different Variable Name To prevent this issue from happening again, choose a variable name that doesn't conflict with MATLAB's built-in functions. For example: [maxCorr, idx] = max(Rc); Now, you can safely use the corr function without any conflicts: R = corr(data1, data2); Best Practices Avoid Using Names of Built-in Functions: Always check MATLAB's documentation to ensure your variable names don't clash with existing functions. Use Descriptive Variable Names: Instead of generic names like corr, use more descriptive names such as maxCorrelation or correlationValue to enhance code readability and maintainability. Summary By clearing the conflicting variable and choosing a unique name for your variables, you can prevent overshadowing built-in functions and ensure your code runs smoothly. Hope this helps! Let me know if you have any more questions.
Apparently, dbstop if warning and dbstop if error are independent, and should be called separately. Calling dbstatus shows their status, and they can be toggled independently.
I don't know what the "sinusoid" is here, but for complex numbers the functions are `abs` and `angle`, not `phase`, according to the doc.
When doing a N-body simulation, one could scale it and if done right I would expect identical behavior just on different time-scales and sizes (with minor differences due to rounding errors). If I for example place particles in a cube of size 10 and (with adjusted speeds) in a cube of size 1, I should get a smaller and faster system that is otherwise identical. This requires smaller step sizes (which are automatically chosen by the solver anyway), but it should overall take the same number of steps to get the same scaled results. With ODE45 in Matlab I get unusable small step-sizes with the smaller system, which forces me to increase the error tolerances. But I don't know how relTol and absTol relate here. In ODE45 absTol/relTol give a threshold which is used in the calculation of the maximum error. With the bigger system the standard error-tolerances (relTol = 1e-3, absTol = 1e-6, so threshold = 1e-3) work fine. I also got good results if I change these error-tolerances by the same factor, so threshold stays the same. But with a scaled system, I suspect that threshold should also change and thus the ratio absTol/relTol. But I have no idea by what amount (or at all). For the small system going to relTol = absTol = 1 seems to work, but I want to make sure that this is equivalent to the bigger system. Can someone give me some insights on how to scale the error tolerances? Would it make sense, in the context of a N-body-simulation, to just use one of these error-tolerances (and set the other one arbitrarily high)?
@Kostas I'm not familiar with CLUT file formats, but from my cursory search, it's either RGBA8888 or RGB565. So you either need an alpha channel, or you need to reduce the color space. Can you update your question with the format you want to use for your example? Getting the lookup table data is simple in MATLAB for the case you've presented, `lut = squeeze(img(1,:,:))`. Now it's just a question of writing the formatted data.
The first thing you should be doing is looking at the orange underlined warning in your editor about data_class growing with each loop iteration. Initialising it before all of your loops with this saves a large portion of the runtime immediately Pre-allocate data_class before the loops: szout = [sz, [numel(edge_X),numel(edge_Y)]-1]; data_class = NaN(szout); But the main bottleneck is calling histcounts2 on every value individually, you can make large time savings by bringing it outside of the ii/ij loops, and instead of using the first input as a count of 1 for the bin it's in, use the 4th and 5th outputs which store the bin each value should go into. In your case this is the row and column indices. Here are some timings: Baseline code: 20.53sec Pre-allocating data_class: 7.75sec (-62% total runtime) De-nest histcounts2: 0.53sec (-97% total runtime) Only assign non-zero values: 0.10sec (-99.5% total runtime) De-nest histcounts2 sz = size(data); szout = [sz, [numel(edge_X),numel(edge_Y)]-1]; data_class = NaN(szout); for ix = 1:sz(1) for iy = 1:sz(2) g_X = data_X(ix, iy, :, :); g_Y = data_Y(ix, iy, :, :); [~,~,~,bx,by] = histcounts2(g_X, g_Y, edge_X, edge_Y); bx = squeeze(bx); by = squeeze(by); g_data = squeeze( data(ix, iy, :, :) ); for ii = 1:sz(3) for ij = 1:sz(4) g_new = zeros(szout(end-1:end)); g_new(bx(ii,ij),by(ii,ij)) = g_data(ii,ij); data_class(ix,iy,ii,ij,:,:) = g_new; end end end end Further, you don't need to initialise the array of zeros g_new for every slice just to set one value. Instead, initialise data_class as a matrix of zeros and just override the specific values you're interested in: Only assign non-zero values sz = size(data); szout = [sz, [numel(edge_X),numel(edge_Y)]-1]; data_class = zeros(szout); for ix = 1:sz(1) for iy = 1:sz(2) g_X = data_X(ix, iy, :, :); g_Y = data_Y(ix, iy, :, :); [~,~,~,bx,by] = histcounts2(g_X, g_Y, edge_X, edge_Y); bx = squeeze(bx); by = squeeze(by); g_data = squeeze( data(ix, iy, :, :) ); for ii = 1:sz(3) for ij = 1:sz(4) data_class(ix,iy,ii,ij,bx(ii,ij),by(ii,ij)) = g_data(ii,ij); end end end end You could do something with sub2ind to get rid of the ii/ij loops entirely, but in a quick test that didn't show any performance over just using the loops.
In Matlab, I need to perform a calculation. There are two ways I can do this calculation, but I don't know a priori which one will be easier. One way will take the computer a millisecond to finish, and the other will take minutes. So I need a way to ask Matlab how long it's been stuck on one line of code. Something like this: start timer run this line of code if 0.1 second has passed stop and run this line of code end Is this possible? Note that this question https://stackoverflow.com/questions/21925137/how-can-i-abort-program-execution-in-matlab is not relevant because I don't want to actually stop the program.
Calculating Eigenvalues of 3D-functions with eigs
Patching a color gradient with respect to given angular data
Use MATLAB to execute Excel What-If Goal Seek Analysis
I am trying to make a multiplication table for an assignment but anytime I run the script, the formatting is messed up and it wouldn't repeat num1 for every new line. (What I want this code to do is that the first number is a normal scalar (ie.12) and then the minimum and maximum is a bunch of different numbers (ie. 2-20), I want it to print 12x2=24 , 12x3 = 24, ... 12x20= 240) This is the code I tried and for some reason its just always messed up. num1 = input('What is your first number?:'); minnum2 = input ('What is your minimum of the second number?:'); maxnum2 = input('What is your maximum of the second number?:'); num2 = minnum2:1:maxnum2; product = num1 * num2; table = [num2;product]; fprintf ('%f x %2.0f = %3.0f \n',num1, table); The first line would always be correct but after that it just all messes up.
OK, great, that makes sense. I will try that.
Matlab spectrogram to matplotlib spectrum
What error does that produce? Did you try `sym('-10^(-10^308)')`?
Just to be clear, those are user-contributed tools, not from MATLAB. You should probably ask the authors.
I found the answer. thanks for your effort my friend
Doesn't seem like scaling issue. Data went up 25x. Time went up less than that. You can try adding periodic print to screen messages like `Nreport=round(length(x)/100);` ... `if not(rem(i,Nreport);` ...`disp(['Calculating eta for i = ',i,' j = ',j)`. That's something I'd typically do for any large amount of calculations or repeated procedures.
Matlab resampling hypothesis test correlation - Why Do the P-Value and Confidence Interval for My Correlation Test Give Different Results?
It’s a method of a class. You need to create an object of that class and then call the object’s method. In MATLAB, functions don’t need to be methods of a class. You can make regular old functions. It’s not Java.
QR codes are located, basically, by scanning across the image and looking for a pattern of edges of relative distance 1,1,3,1,1, which is characteristic of the "finder patterns". this approach is detailed in the original paper/specification. your approach looks ad-hoc. I don't see that leading far.
Matlab standalon application with loaded .net framework
Have you considered using the [`symbolic`](https://www.mathworks.com/help/symbolic/create-symbolic-numbers-variables-and-expressions.html) data type and [`vpa`](https://www.mathworks.com/help/symbolic/sym.vpa.html)? Computation will be slower, but you get arbitrary precision
`cell{:}` is the same as `cell{1}, cell{2}, cell{3}, …`. So it creates one input argument to `cat` for every element in the cell array. Because it’s a comma-separated list, you can’t assign it to a variable, only the first element will be assigned. Like saying `a=1, 1, 1`, the variable will be 1, and the other two 1s will be lost (comma is a statement separator there).
Datatype error making PostgreSQL query from matlab
How to accurately draw a Bode diagram of a control system in MATLAB in the case of its matrix being ill-conditioned?
Matlab code to generate the Phase and angle of the sinusoid?
Obtain origin of warning issued by m-functions with code generation
I am attempting to declutter my MATLAB app code by separating some of the initialization into separate .m files. For this I have set up various files for each type of component (e.g. a file for buttons, graph, etc.). I am attempting to access a function in my master initialize file from the file for buttons. My code goes as follows in the buttons .m file goes as follow: classdef buttons < handle methods %initializes the UI function buttonCreate(app) %Create file load 1 app.fileload1 = uibutton(app.gridLayout, 'push'); app.fileload1.FontSize = 36; app.fileload1.Layout.Row = [8 9]; app.fileload1.Layout.Column = 1; app.fileload1.Text = 'Load 1'; %proceeds to create the rest of the buttons end end end Now I attempt to access the buttonCreate() function in my master initialize file initialize.m: classdef initialize < handle properties fig gridLayout axes fileload1 end methods %initializes the UI function init(app) %create canvas import buttons.*; fig = uifigure; fig.Position = [100 100 1920 1080]; movegui(fig,'center'); fig.Name = "Audio Editor"; %Create grid layout gridLayout = uigridlayout(fig); gridLayout.ColumnWidth = {'1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x'}; gridLayout.RowHeight = {'1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x'}; buttonCreate(app); end end %code for calling and deleting methods %calls code to create canvas upon app start function app = initialize init(app) end %removes the app and deletes app.fig function delete(app) delete(app.fig); end end end Error in initialize/init (line 41) buttonCreate(app); ^^^^^^^^^^^^^^^^^^ Error in initialize (line 54) init(app) ^^^^^^^^^ This resulted in the UIFigure still being created, but with no button and the terminal giving the error given above.
What is the purpose of the second file? What do you expect to gain by adding the “`(t)`” everywhere?
Adding a comment here a similar thread I found in MATLAB Answers. https://in.mathworks.com/matlabcentral/answers/414694-how-can-i-protect-the-intellectual-property-of-my-simulink-model
I see two issues with this approach, 1) I assume you are printing your coefficients into the console and copying them into matlab. The issue with this is that for visualization the values maybe truncated which can lead to stability problems especially for higher order IIR filters. Rather save the coeffs in python and load them in Matlab. 2) Excluding the zeros and changing the indexes of the nominator coefficients will change the filter characteristics, compare it using matlabs `fvtool`. Minor comments, for higher order IIR filters it is recommended to use SOS structures for stability.
Separately, since you are not using a [minimal example](https://stackoverflow.com/help/minimal-reproducible-example), consider commenting the type and size of your variables in your question. Indeed checking what your variables are is required for understanding your question. So help others help you!
How to demodulate an AM signal in MATLAB?
That's a neat way to access the call stack. But it is not exactly what I am looking for as it pauses the execution. Instead I am looking for a way to inform the user of specific conditions in a m-function identified by its path. I use a warning for that but I could also just print the message. I think I haven't explained this point well enough.
For large step sizes, the leading error term, which behaves according to the error, competes with the higher-degree terms. For small step-sizes the numerical error competes with the accumulated floating-point error. You want the segment between these extremes. For stiff ODE or methods with small stability regions this segment might shrink to nothing, which has effects like you described.
@PeterCordes Yes, it does answer the question. MATLAB makes no distinction. "MATLAB will rely on the operating system to schedule processes across the available cores." That is, it is the OS that decides where each process runs. MATLAB just launches the processes.
% Parameters for the Kármán–Trefftz transformation beta = .491; % Offset from the origin (adjust for trailing edge) n = 4; % Increase for sharper features b = -0.3; % Adjust for different airfoil characteristics % Circle in the complex plane theta = linspace(0, 2*pi, 100); % Angle for the circle zeta = beta + exp(1i * theta); % Circle centered at (beta, 0) with radius 1 % Kármán–Trefftz transformation z = (n*b*(zeta + b).^n + (zeta - b).^n) ./ ((zeta + b).^n - (zeta - b).^n); % Create subplots to display both shapes figure; % Plot the circle subplot(1, 2, 1); plot(real(zeta), imag(zeta), 'b-'); axis equal; % Keep the aspect ratio equal xlabel('Real Part'); ylabel('Imaginary Part'); title('Circle in the Complex Plane'); grid on; % Set y-limits for both plots to be identical ylim([-1.3 1.3]); % Adjust based on your needs xlim([-1 1.9]); % Adjust based on your needs % Plot the airfoil subplot(1, 2, 2); plot(real(z), imag(z), 'r-'); axis equal; % Keep the aspect ratio equal xlabel('Real Part'); ylabel('Imaginary Part'); title('Airfoil Shape via Kármán–Trefftz Transformation'); grid on; % Set y-limits for both plots to be identical ylim([-.5 .5]); % Adjust based on your needs I know the issues is with the formula for z but i dont how to get it to stop to create the sharp edge. the image is the the figure my code prints out. I tried to change the beta,n,&amp; b values which did help from bringing it looking like a egg to a airfoil without sharp edge. If I gove over n=4.999 its starts to cross over x axis.
Isn't the entire point of a N-body simulation to illustrate that simulations like this are chaotic in nature and minuscule tolerance mistakes (beyond what is humanly/computationally tractable) will create a wildly different result? i.e. are you not just asking "how to ignore chaos theory"?
In my experience, GPU FFT is not faster than a good multi-threaded CPU FFT. MATLAB's FFT is super fast.
Your MATLAB version is important here. Before R2014b, there was only one `colomap` per `figure`. Starting at R2014b, each `axes` has it's own colormap (still, only one per `axes`). There is no standard MATLAB way to have more than one `colormap` on an `axes`, you will have to resort to some manual tricks. The 2 most used methods are: (1) use 2 different `axes`, each with their respective `colormap`, then surperpose them. You will have to manually link axis limits, adjust colorbar positions and Z-order of the axis to get a desired result. This works OK for 2D plots, 3D surfaces may not mix well
I'm building my Matlab code as a standalone application (exe) using the following command mcc -v -N -p -m runMyCode.m I use Matlab 2022b which supports .net 5+. When I run runMyCode.exe then I log the output of dotnetenv. I states that .NET Framework 4.0.30319.42000 is loaded. The problem is that for some reason .NET is "loaded" at the entry point so if I add dotnetenv("core"), it produces an error: .NET is loaded. To change the environment, restart MATLAB then call dotnetenv. If I run the exe again, .NET Framework is still loaded. What I noticed is that if I open Matlab, run dotnetenv("core") and then run mcc then .NET Core is loaded within the exe. Is there a way to tell mcc what .NET version to be used for building the exe or at least build it in a way that .NET is not loaded?
Do you want lookup with interpolation or without? —— In what form do you have your data in MATLAB? Can you post some code that represents the data?
replace 'error += ..' with 'error=error+.. '
How can I create a 3D map of the glacier (bedrock + glacier surface + debris surface) with each a different colormap in Matlab? I tried several things but it does not work. Only 1 colormap is used and not a separate one for each distinct layer. How can I solve this? close all; clear; clc; % Load data bedrock = double(geotiffread('bedrock_oct2023.tif')); icethick = ncread(file_name, 'icethick'); h_debris = ncread(file_name, 'h_debris'); % Define grid for plotting [X, Y] = meshgrid(1:size(bedrock, 2), 1:size(bedrock, 1)); % Compute initial elevations elevation_glacier = bedrock + icethick(:, :, 1); elevation_debris = bedrock + icethick(:, :, 1) + h_debris(:, :, 1); % Create figure figure('Position', [100 100 1200 800]); ax = axes; hold(ax, 'on'); % Define colormaps bedrock_cmap = copper(256); glacier_cmap = winter(256); debris_cmap = parula(256); % Plot initial surfaces with different colormaps manually set using CData bedrock_alpha = double(icethick(:, :, 1) == 0); % Transparent where glacier exists % Plot bedrock bedrock_surf = surf(ax, X, Y, bedrock, 'FaceColor', 'interp', 'FaceAlpha', 1, 'AlphaData', bedrock_alpha); set(bedrock_surf, 'CData', bedrock, 'EdgeColor', 'none'); % Assign bedrock elevation as CData for coloring % Plot glacier glacier_surf = surf(ax, X, Y, elevation_glacier, 'FaceColor', 'interp', 'FaceAlpha', 1); set(glacier_surf, 'CData', elevation_glacier, 'EdgeColor', 'none'); % Assign glacier elevation as CData for coloring % Plot debris debris_surf = surf(ax, X, Y, elevation_debris, 'FaceColor', 'interp', 'FaceAlpha', 1); set(debris_surf, 'CData', elevation_debris, 'EdgeColor', 'none'); % Assign debris elevation as CData for coloring % Set different color limits and colormaps % Bedrock surface color limits caxis([2000 4500]); colormap(ax, bedrock_cmap); % Freeze the colormap for bedrock so that changes to colormap do not affect it freezeColors(bedrock_surf); % Glacier surface color limits caxis([2000 4500]); colormap(ax, glacier_cmap); freezeColors(glacier_surf); % Debris surface color limits caxis([2000 4500]); colormap(ax, debris_cmap); freezeColors(debris_surf); % Add glacier mask glacier_mask = double(icethick(:, :, 1) &gt; 0); % Convert mask to double for coloring glacier_mask_elev = bedrock + icethick(:, :, 1); mask_surf = surf(ax, X, Y, glacier_mask_elev, 'FaceAlpha', 1, 'EdgeColor', 'w'); set(mask_surf, 'FaceColor', 'white'); % Set mask color to white directly % Set transparency where elevation equals bedrock (no ice) alpha_data = (glacier_mask_elev ~= bedrock); set(mask_surf, 'AlphaData', alpha_data, 'FaceAlpha', 'interp'); % Add colorbars cb1 = colorbar('Position', [0.92 0.1 0.02 0.2]); colormap(cb1, bedrock_cmap); title(cb1, 'Bedrock'); cb2 = colorbar('Position', [0.92 0.4 0.02 0.2]); colormap(cb2, glacier_cmap); title(cb2, 'Glacier'); cb3 = colorbar('Position', [0.92 0.7 0.02 0.2]); colormap(cb3, debris_cmap); title(cb3, 'Debris'); % Set axis properties xlabel('X (m)'); ylabel('Y (m)'); zlabel('Elevation (m)'); set(gca, 'XDir', 'reverse', 'FontSize', 14); title('3D View of Glacier, Debris, Bedrock, and Glacier Mask Surface'); set(gcf, 'color', 'white'); % Set view and lighting view(45, 35); shading interp; camlight('left'); camlight('right'); material dull; % Adjust material properties lighting phong; I have tried the code above but the plot generates only 1 colormap for all 3 layers (bedrock + glacier + debris). I want the plot to have a distinct colormap for each of the layers.
Well, there is some API test E2E scenarios e.g. 1/ create test workspace - 2/ create test board in this workspace use workspace ID as parameter - 3/ delete test board by created ID in this workspace - 4/ delete test workspace by ID. The goal is to have one scenario as TestClass with every step as a method, so once i get test ID in step 1/ only after test workspace is created, i need to store it for test 2/ and so on. I know that is is somehow against the concept of unit testing, but ti'd like to make it by analog of other test framework where it worked
And preallocate `fourmatrix` to save some more time
Test cases are supposed to be independent. They have to do exactly the same thing every time, even if you run one individually, or if you add or remove other test cases. So whatever you are planning to do with this persistent value is contrary to the concept of unit tests. Maybe if you explain your ultimate goal, we can point you in the right direction.
@beaker Thank you very much for the hints. It was nice to find your link to image -> graph conversion uses same idea I had had used already at the time.
I'm going to say this *no converter found for element oid 1700* is coming from `octave` as I don't see `uuid` as one of the [built in types](https://docs.octave.org/latest/Built_002din-Data-Types.html). The only I can think of at this time is have `public.fn_func()` take a `text` argument and then do the cast to `uuid` in the function.
Scaling a N-body-simulation and error tolerances
In the process of using MATLAB for image digit recognition, due to task requirements, I needed to use a BP neural network. I generated 500 images of digits from 0 to 9 and set up a two-layer neural network, but the prediction results have not reached 90%. I'm a beginner in machine learning, and I would greatly appreciate any guidance. two-layer result clc; clear; % Load training data trainData = imageDatastore('D:\Matlab_Project\CourseProject\BP\Datasets\train', ... 'IncludeSubfolders', true, ... 'FileExtensions', '.jpg', ... 'LabelSource', 'foldernames'); % Change extension to .jpg testData = imageDatastore('Datasets/test', 'LabelSource', 'foldernames', 'FileExtensions', '.png'); imageSize = [32, 32]; numImages = numel(trainData.Files); % Define image augmentation parameters imageAugmenter = imageDataAugmenter('RandRotation', [-20, 20], 'RandXReflection', true); % Create augmented image data store augmentedTrainData = augmentedImageDatastore(imageSize, trainData, 'DataAugmentation', imageAugmenter); % Read augmented images trainFeatures = zeros(numImages, prod(imageSize)); for i = 1:numImages img = readByIndex(augmentedTrainData, i); % Read data by index trainImg = cell2mat(img{1, 1}); % Get image data Img = double(trainImg); % Convert to grayscale and normalize to [0, 1] train_img = (Img - min(Img(:))) / (max(Img(:)) - min(Img(:))); % Normalize to [0, 1] trainFeatures(i, :) = train_img(:)'; % Flatten normalized image and store end % Initialize labels trainLabels = zeros(numImages, 1); for i = 1:numImages % Get file path and extract label name = trainData.Labels(i); trainLabels(i) = double(name)-1; % Convert label to number and subtract 1 to match MATLAB indexing end % Generate a random permutation index randomIdx = randperm(numImages); % Shuffle training data and labels according to random index shuffledFeatures = trainFeatures(randomIdx, :); shuffledLabels = trainLabels(randomIdx, :); % Split training and validation sets trainRatio = 0.8; numTrainImages = round(numImages * trainRatio); trainFeatures = shuffledFeatures(1:numTrainImages, :); trainLabels = shuffledLabels(1:numTrainImages, :); % Assuming valFeatures is validation set features valFeatures = shuffledFeatures(numTrainImages+1:end, :); % Validation set features valLabels = shuffledLabels(numTrainImages+1:end, :); % Initialize the neural network inputLayer = size(trainFeatures, 2); hiddenLayer1Size = 9; % First hidden layer node count hiddenLayer2Size = 1; % Second hidden layer node count OutputLayerSize = 10; % Corresponding to 10 labels for 0~9 % Initialize feedforward weights and biases W1 = randn(hiddenLayer1Size, inputLayer) * sqrt(2 / inputLayer); % He initialization b1 = zeros(hiddenLayer1Size, 1); % Hidden layer bias initialized to 0 W2 = randn(hiddenLayer2Size, hiddenLayer1Size) * sqrt(2 / hiddenLayer1Size); % He initialization b2 = zeros(hiddenLayer2Size, 1); % Second hidden layer bias initialized to 0 W3 = randn(OutputLayerSize, hiddenLayer2Size) * sqrt(2 / hiddenLayer2Size); % He initialization b3 = zeros(OutputLayerSize, 1); % Output layer bias initialized to 0 batchSize = 20; % Number of samples for batch learning valPredictions = zeros(size(valLabels)); % Initialize validation set predictions numValBatches = ceil(size(valFeatures, 1) / batchSize); % Calculate validation set batch count totalValLoss = 0; for batch = 1:numValBatches % Calculate indices for the current batch startIdx = (batch - 1) * batchSize + 1; endIdx = min(batch * batchSize, size(valFeatures, 1)); % Get features for the current batch X_val_batch = valFeatures(startIdx:endIdx, :)'; % Input, dimensions [inputSize, batchSize] % Forward propagation Z1_val = W1 * X_val_batch + b1; % Weighted input for first hidden layer A1_val = activation(Z1_val, "sigmoid"); % Activation output for first hidden layer Z2_val = W2 * A1_val + b2; % Weighted input for second hidden layer A2_val = activation(Z2_val, "sigmoid"); % Activation output for second hidden layer Z3_val = W3 * A2_val + b3; % Weighted input for output layer A3_val = softmax(Z3_val); % Activation output for output layer % Calculate cross-entropy loss idx = sub2ind(size(A3_val), valLabels(startIdx:endIdx)' + 1, 1:size(A3_val, 2)); batchLoss = -mean(log(A3_val(idx))); % Cross-entropy loss calculation % Accumulate batch loss into total loss totalValLoss = totalValLoss + batchLoss; end % Calculate average validation loss averageValLoss = totalValLoss / numValBatches; disp(['Initial Validation Loss: ', num2str(averageValLoss)]); % Backpropagation learningRate = 0.0001; epochNum = 1000; bestValLoss = inf; numTrainImages = size(trainLabels,1); batchSize = 20; trainLosses = zeros(epochNum, 1); % Store training loss for each epoch valLosses = zeros(epochNum, 1); % Store validation loss for each epoch numBatches = ceil(numTrainImages / batchSize); numBatches = size(numBatches,1); lambda = 0.019; % Regularization strength % Adam optimizer parameters alpha = 0.001; % Initial learning rate beta1 = 0.9; beta2 = 0.999; epsilon = 1e-8; % Initialize parameters mW1 = zeros(size(W1)); vW1 = zeros(size(W1)); mb1 = zeros(size(b1)); vb1 = zeros(size(b1)); mW2 = zeros(size(W2)); vW2 = zeros(size(W2)); mb2 = zeros(size(b2)); vb2 = zeros(size(b2)); mW3 = zeros(size(W3)); vW3 = zeros(size(W3)); mb3 = zeros(size(b3)); vb3 = zeros(size(b3)); % Backpropagation for epoch = 1:epochNum epochLoss = 0; for batch = 1:numBatches % Calculate the index for the current batch startIdx = (batch - 1) * batchSize + 1; endIdx = min(batch * batchSize, numTrainImages); % Get the data for the current batch X_batch = trainFeatures(startIdx:endIdx, :)'; % Input Y_batch = trainLabels(startIdx:endIdx)'; % Labels % Forward propagation Z1 = W1 * X_batch + b1; % Weighted input for the first hidden layer A1 = activation(Z1, "sigmoid"); % Activation output for the first hidden layer Z2 = W2 * A1 + b2; % Weighted input for the second hidden layer A2 = activation(Z2, "sigmoid"); % Activation output for the second hidden layer Z3 = W3 * A2 + b3; % Weighted input for the output layer A3 = softmax(Z3); % Activation output for the output layer % Calculate error idx = sub2ind(size(A3), Y_batch + 1, 1:size(A3, 2)); epsilon = 1e-10; error = -mean(log(A3(idx) + epsilon)); % Use average cross-entropy epochLoss = epochLoss + error; % Backpropagation delta3 = A3; % Initialize delta3 as the probabilities from A3 delta3(sub2ind(size(A3), Y_batch + 1, 1:size(A3, 2))) = delta3(sub2ind(size(A3), Y_batch + 1, 1:size(A3, 2))) - 1; delta2 = (W3' * delta3) .* diff_activation(A2, "sigmoid"); % Error term for the second hidden layer delta1 = (W2' * delta2) .* diff_activation(A1, "sigmoid"); % Error term for the first hidden layer % Calculate gradients gradW3 = delta3 * A2' / size(A3, 2) + lambda * W3; % Include L2 regularization gradb3 = mean(delta3, 2); gradW2 = delta2 * A1' / size(A3, 2) + lambda * W2; % Include L2 regularization gradb2 = mean(delta2, 2); gradW1 = delta1 * X_batch' / size(A3, 2) + lambda * W1; % Include L2 regularization gradb1 = mean(delta1, 2); % Update first moment estimates mW1 = beta1 * mW1 + (1 - beta1) * gradW1; mb1 = beta1 * mb1 + (1 - beta1) * gradb1; mW2 = beta1 * mW2 + (1 - beta1) * gradW2; mb2 = beta1 * mb2 + (1 - beta1) * gradb2; mW3 = beta1 * mW3 + (1 - beta1) * gradW3; mb3 = beta1 * mb3 + (1 - beta1) * gradb3; % Update second moment estimates vW1 = beta2 * vW1 + (1 - beta2) * (gradW1 .^ 2); vb1 = beta2 * vb1 + (1 - beta2) * (gradb1 .^ 2); vW2 = beta2 * vW2 + (1 - beta2) * (gradW2 .^ 2); vb2 = beta2 * vb2 + (1 - beta2) * (gradb2 .^ 2); vW3 = beta2 * vW3 + (1 - beta2) * (gradW3 .^ 2); vb3 = beta2 * vb3 + (1 - beta2) * (gradb3 .^ 2); % Compute bias-corrected estimates mW1_hat = mW1 / (1 - beta1^epoch); mb1_hat = mb1 / (1 - beta1^epoch); mW2_hat = mW2 / (1 - beta1^epoch); mb2_hat = mb2 / (1 - beta1^epoch); mW3_hat = mW3 / (1 - beta1^epoch); mb3_hat = mb3 / (1 - beta1^epoch); vW1_hat = vW1 / (1 - beta2^epoch); vb1_hat = vb1 / (1 - beta2^epoch); vW2_hat = vW2 / (1 - beta2^epoch); vb2_hat = vb2 / (1 - beta2^epoch); vW3_hat = vW3 / (1 - beta2^epoch); vb3_hat = vb3 / (1 - beta2^epoch); % Update weights and biases W1 = W1 - alpha * mW1_hat ./ (sqrt(vW1_hat) + epsilon); b1 = b1 - alpha * mb1_hat ./ (sqrt(vb1_hat) + epsilon); W2 = W2 - alpha * mW2_hat ./ (sqrt(vW2_hat) + epsilon); b2 = b2 - alpha * mb2_hat ./ (sqrt(vb2_hat) + epsilon); W3 = W3 - alpha * mW3_hat ./ (sqrt(vW3_hat) + epsilon); b3 = b3 - alpha * mb3_hat ./ (sqrt(vb3_hat) + epsilon); end % Calculate training loss, including L2 regularization trainLosses(epoch) = (epochLoss / numBatches) + (lambda / 2) * (norm(W1, 'fro')^2 + norm(W2, 'fro')^2 + norm(W3, 'fro')^2); % Validation loss calculation (without Dropout) valPredictions = zeros(size(valLabels)); % Validation loss calculation (without loops) Z1_val = W1 * valFeatures' + b1; A1_val = activation(Z1_val, "sigmoid"); Z2_val = W2 * A1_val + b2; A2_val = activation(Z2_val, "sigmoid"); Z3_val = W3 * A2_val + b3; A3_val = softmax(Z3_val); % Select the actual class probabilities for each sample as the basis for validation loss calculation valIdx = sub2ind(size(A3_val), valLabels' + 1, 1:size(A3_val, 2)); valLoss = -mean(log(A3_val(valIdx) + epsilon)); % Calculate average cross-entropy loss valLoss = valLoss + (lambda / 2) * (norm(W1, 'fro')^2 + norm(W2, 'fro')^2 + norm(W3, 'fro')^2); % Include regularization in validation loss valLosses(epoch) = valLoss; % Predict classes [~, predictedLabels] = max(A3_val, [], 1); valPredictions = predictedLabels - 1; % Subtract 1 from the index to match label range 0-9 disp(['Epoch: ' num2str(epoch) ', Training Error: ' num2str(epochLoss / numBatches) ', Validation Loss: ' num2str(valLoss)]); end % Plot training loss and validation loss curves figure; hold on; plot(trainLosses(1:epoch), 'LineWidth', 1.5); plot(valLosses(1:epoch), 'LineWidth', 1.5); xlabel('Epoch'); ylabel('Loss'); title('Training and Validation Loss'); legend('Training Loss', 'Validation Loss'); grid on; hold off; % Predictions for the test set (without Dropout) %%% Simple test testFeatures = zeros(numel(testData.Files), prod(imageSize)); for i = 1:numel(testData.Files) img = imread(testData.Files{i}); % Use the test dataset files img = imresize(rgb2gray(im2double(img)), imageSize); % Normalize and resize img = (img - mean(img(:))) / std(img(:)); % Standardize to zero mean and unit variance testFeatures(i, :) = img(:)'; % Flatten the image and store it end testPredictions = zeros(size(testFeatures, 1), OutputLayerSize); for j = 1:size(testFeatures, 1) X_test = testFeatures(j, :)'; % Get the feature vector for a single test sample % Forward propagation (without Dropout) Z1_test = W1 * X_test + b1; A1_test = activation(Z1_test, "sigmoid"); Z2_test = W2 * A1_test + b2; A2_test = activation(Z2_test, "sigmoid"); % Activation output for the second hidden layer Z3_test = W3 * A2_test + b3; A3_test = softmax(Z3_test); testPredictions(j, :) = A3_test; % Store the output probabilities end % Get the predicted labels based on the test predictions [~, finalPredictions] = max(testPredictions, [], 2); finalPredictions = finalPredictions - 1; % Convert to label format function y = activation(x, method) %% Options: sigmoid, tanh, relu, softmax if strcmp(method, "sigmoid") y = logsig(x); % Sigmoid activation function elseif strcmp(method, "tanh") y = tanh(x); % Tanh activation function elseif strcmp(method, "relu") y = max(0, x); % ReLU activation function elseif strcmp(method, "softmax") % expX = exp(x - max(x)); % Adjustment for numerical stability % y = expX / sum(expX); % Softmax activation function y = softmax(x); else error('Unsupported activation method. Choose from: sigmoid, tanh, relu, softmax.'); end end function y = diff_activation(x, method) % Gradient of activation functions: sigmoid, tanh, relu, softmax if strcmp(method, "sigmoid") y = (x) .* (1 - x); % Derivative of sigmoid elseif strcmp(method, "tanh") y = 1 - (x).^2; % Derivative of tanh elseif strcmp(method, "relu") y = x > 0; % Derivative of ReLU: 1 for parts greater than 0, 0 otherwise elseif strcmp(method, "softmax") % Derivative of softmax: diagonal part s = exp(x) ./ sum(exp(x)); y = diag(s) - (s * s'); else error('Unsupported activation method. Choose from: sigmoid, tanh, relu, softmax.'); end end I also tried using a single-layer neural network, but the results were unsatisfactory. single-layer result clc; clear; % Load training data trainData = imageDatastore('D:\Matlab_Project\CourseProject\BP\Datasets\train', ... 'IncludeSubfolders', true, ... 'FileExtensions', '.jpg', ... 'LabelSource', 'foldernames'); % Change the extension to .jpg testData = imageDatastore('Datasets/test', ... 'IncludeSubfolders', true, ... 'FileExtensions', '.png', ... 'LabelSource', 'foldernames'); % Test data remains unchanged imageSize = [32, 32]; numImages = numel(trainData.Files); % Define image augmentation parameters imageAugmenter = imageDataAugmenter('RandRotation', [-20, 20], 'RandXReflection', true); % Create augmented image data storage augmentedTrainData = augmentedImageDatastore(imageSize, trainData, 'DataAugmentation', imageAugmenter); % Read augmented images trainFeatures = zeros(numImages, prod(imageSize)); for i = 1:numImages img = readByIndex(augmentedTrainData, i); % Use readByIndex to read data by index trainImg = cell2mat(img{1, 1}); % Retrieve image data Img = double(trainImg); % Convert to grayscale and normalize to [0, 1] train_img = (Img - min(Img(:))) / (max(Img(:)) - min(Img(:))); % Normalize to [0, 1] trainFeatures(i, :) = train_img(:)'; % Flatten and store the normalized image end % Initialize labels trainLabels = zeros(numImages, 1); for i = 1:numImages % Retrieve file path and extract label name = trainData.Labels(i); trainLabels(i) = double(name)-1; % Convert label to a number and subtract 1 to fit MATLAB indexing end % Generate a random shuffle index randomIdx = randperm(numImages); % Shuffle training data and labels according to the random index shuffledFeatures = trainFeatures(randomIdx, :); shuffledLabels = trainLabels(randomIdx, :); % Split training and validation sets trainRatio = 0.8; numTrainImages = round(numImages * trainRatio); trainFeatures = shuffledFeatures(1:numTrainImages, :); trainLabels = shuffledLabels(1:numTrainImages, :); % Assume valFeatures are validation set features valFeatures = shuffledFeatures(numTrainImages+1:end, :); % Validation set features valLabels = shuffledLabels(numTrainImages+1:end, :); % Initialize neural network inputLayer = size(trainFeatures, 2); hiddenLayerSize = 9; OutputLayerSize = 10; % Corresponds to 10 labels (0~9) % Forward feed W1 = randn(hiddenLayerSize, inputLayer) * sqrt(2 / inputLayer); % He initialization W2 = randn(OutputLayerSize, hiddenLayerSize) * sqrt(2 / hiddenLayerSize); % He initialization b1 = zeros(hiddenLayerSize, 1); % Initialize hidden layer bias to 0 b2 = zeros(OutputLayerSize, 1); % Initialize output layer bias to 0 batchSize = 50; % Number of samples per batch for batch learning valPredictions = zeros(size(valLabels)); % Initialize validation predictions numValBatches = ceil(size(valFeatures, 1) / batchSize); % Calculate validation batches totalValLoss = 0; for batch = 1:numValBatches % Calculate current batch index startIdx = (batch - 1) * batchSize + 1; endIdx = min(batch * batchSize, size(valFeatures, 1)); % Get current batch features X_val_batch = valFeatures(startIdx:endIdx, :)'; % Input, dimensions [inputSize, batchSize] % Forward propagation Z1_val = W1 * X_val_batch + b1; % Weighted input for hidden layer A1_val = activation(Z1_val, "sigmoid"); % Hidden layer activation output Z2_val = W2 * A1_val + b2; % Weighted input for output layer % Apply softmax activation function A2_val = softmax(Z2_val); % Calculate cross-entropy loss idx = sub2ind(size(A2_val), valLabels(startIdx:endIdx)' + 1, 1:size(A2_val, 2)); batchLoss = -mean(log(A2_val(idx))); % Cross-entropy loss calculation % Accumulate batch loss to total loss totalValLoss = totalValLoss + batchLoss; end % Calculate average validation loss averageValLoss = totalValLoss / numValBatches; disp(['Initial Validation Loss: ', num2str(averageValLoss)]); % Backpropagation learningRate = 0.01; epochNum = 1000; bestValLoss = inf; numTrainImages = size(trainLabels, 1); batchSize = 40; trainLosses = zeros(epochNum, 1); % Store training loss for each epoch valLosses = zeros(epochNum, 1); % Store validation loss for each epoch numBatches = ceil(numTrainImages / batchSize); lambda = 0.005; % Regularization strength % Adam optimizer parameters alpha = 0.001; % Initial learning rate beta1 = 0.9; beta2 = 0.999; epsilon = 1e-8; % Initialize parameters mW1 = zeros(size(W1)); vW1 = zeros(size(W1)); mb1 = zeros(size(b1)); vb1 = zeros(size(b1)); mW2 = zeros(size(W2)); vW2 = zeros(size(W2)); mb2 = zeros(size(b2)); vb2 = zeros(size(b2)); for epoch = 1:epochNum epochLoss = 0; for batch = 1:numBatches % Calculate current batch index startIdx = (batch - 1) * batchSize + 1; endIdx = min(batch * batchSize, numTrainImages); % Get current batch data X_batch = trainFeatures(startIdx:endIdx, :)'; % Input Y_batch = trainLabels(startIdx:endIdx)'; % Label % Forward propagation Z1 = W1 * X_batch + b1; % Weighted input for hidden layer A1 = activation(Z1, "sigmoid"); % Hidden layer activation output Z2 = W2 * A1 + b2; % Weighted input for output layer A2 = softmax(Z2); % Output layer activation output % Compute error idx = sub2ind(size(A2), Y_batch + 1, 1:size(A2, 2)); error = -mean(log(A2(idx) + epsilon)); % Use mean cross-entropy epochLoss = epochLoss + error; % Backpropagation delta2 = A2; % Initialize delta2 as probabilities in A2 delta2(sub2ind(size(A2), Y_batch + 1, 1:size(A2, 2))) = delta2(sub2ind(size(A2), Y_batch + 1, 1:size(A2, 2))) - 1; delta1 = (W2' * delta2) .* diff_activation(A1, "sigmoid"); % Hidden layer error term % Calculate gradients gradW2 = delta2 * A1' / size(A2, 2) + lambda * W2; % Include L2 regularization gradb2 = mean(delta2, 2); gradW1 = delta1 * X_batch' / size(A2, 2) + lambda * W1; % Include L2 regularization gradb1 = mean(delta1, 2); % Update first moment estimates mW1 = beta1 * mW1 + (1 - beta1) * gradW1; mb1 = beta1 * mb1 + (1 - beta1) * gradb1; mW2 = beta1 * mW2 + (1 - beta1) * gradW2; mb2 = beta1 * mb2 + (1 - beta1) * gradb2; % Update second moment estimates vW1 = beta2 * vW1 + (1 - beta2) * (gradW1 .^ 2); vb1 = beta2 * vb1 + (1 - beta2) * (gradb1 .^ 2); vW2 = beta2 * vW2 + (1 - beta2) * (gradW2 .^ 2); vb2 = beta2 * vb2 + (1 - beta2) * (gradb2 .^ 2); % Calculate bias-corrected estimates mW1_hat = mW1 / (1 - beta1^epoch); mb1_hat = mb1 / (1 - beta1^epoch); mW2_hat = mW2 / (1 - beta1^epoch); mb2_hat = mb2 / (1 - beta1^epoch); vW1_hat = vW1 / (1 - beta2^epoch); vb1_hat = vb1 / (1 - beta2^epoch); vW2_hat = vW2 / (1 - beta2^epoch); vb2_hat = vb2 / (1 - beta2^epoch); % Update weights and biases W1 = W1 - alpha * mW1_hat ./ (sqrt(vW1_hat) + epsilon); b1 = b1 - alpha * mb1_hat ./ (sqrt(vb1_hat) + epsilon); W2 = W2 - alpha * mW2_hat ./ (sqrt(vW2_hat) + epsilon); b2 = b2 - alpha * mb2_hat ./ (sqrt(vb2_hat) + epsilon); end % Store training loss for current epoch trainLosses(epoch) = epochLoss / numTrainImages; % Validate on validation set valPredictions = zeros(size(valLabels)); numValBatches = ceil(size(valFeatures, 1) / batchSize); % Reset total validation loss for current epoch totalValLoss = 0; for batch = 1:numValBatches % Calculate current batch index startIdx = (batch - 1) * batchSize + 1; endIdx = min(batch * batchSize, size(valFeatures, 1)); % Get current batch features X_val_batch = valFeatures(startIdx:endIdx, :)'; % Forward propagation on validation set Z1_val = W1 * X_val_batch + b1; % Weighted input for hidden layer A1_val = activation(Z1_val, "sigmoid"); % Hidden layer activation output Z2_val = W2 * A1_val + b2; % Weighted input for output layer % Apply softmax activation for output layer A2_val = softmax(Z2_val); % Calculate cross-entropy loss for the batch idx = sub2ind(size(A2_val), valLabels(startIdx:endIdx)' + 1, 1:size(A2_val, 2)); batchLoss = -mean(log(A2_val(idx) + epsilon)); % Accumulate batch loss into total validation loss totalValLoss = totalValLoss + batchLoss; end % Calculate average validation loss for the epoch averageValLoss = totalValLoss / numValBatches; valLosses(epoch) = averageValLoss; % Display loss information disp(['Epoch ', num2str(epoch), ' - Training Loss: ', num2str(trainLosses(epoch)), ... ' - Validation Loss: ', num2str(averageValLoss)]); % Early stopping: save model if validation loss improves if averageValLoss < bestValLoss bestValLoss = averageValLoss; bestW1 = W1; bestb1 = b1; bestW2 = W2; bestb2 = b2; patienceCounter = 0; % Reset patience counter if validation improves else patienceCounter = patienceCounter + 1; if patienceCounter >= patience disp('Early stopping triggered.'); break; end end end % Plot training and validation loss over epochs figure; plot(1:epoch, trainLosses(1:epoch), '-o', 'DisplayName', 'Training Loss'); hold on; plot(1:epoch, valLosses(1:epoch), '-x', 'DisplayName', 'Validation Loss'); xlabel('Epoch'); ylabel('Loss'); legend; title('Training and Validation Loss'); grid on; % Load best model weights W1 = bestW1; b1 = bestb1; W2 = bestW2; b2 = bestb2; disp('Training completed. Best validation loss: '); disp(bestValLoss);
That isn't the descriptive bit of the error message, what's the full error message with the cause description?
I can't advise on the Matlab but I would hazard a guess that the chess matrix is to shift the phase centre after the convolution. Otherwise the output of the convolution will be centred on the natural phase centre of the FFT at (0,0). I suspect that your problem with accuracy is because `1/sqrt(eta^2+nu^2)` only decreases slowly so that truncation errors are significant when you have a very finite grid. Try it with `exp(-x^2)` or without the `sqrt()` and I would expect much better agreement with theory.
I think it would be good if you re-read your question with fresh eyes, and imagine what someone without your baggage could understand of this. I *think* your are talking about images here, but you don’t use that word anywhere. I *think* you have a labeled image and want to display it in some specific way. Note especially that “matrix” is a mathematical term, with a very specific meaning, and doesn’t normally contain “data”.
According to Simulink documentation the workflow for model/subsystem for IP protection we can follow https://in.mathworks.com/help/rtw/ug/generated-s-function-block-deployment.html.
I suspect it depends on the OS to some extent. Before Win11 the E&P core support wasn't really there. I'd hazard a guess that it uses E-core(s) for the user interface and anything that is remotely CPU bound goes to a P-core. I also expect that due to hyper threading MATLAB maxNumCompThreads default may be more than physical cores and less than twice that number. I find using around 1.6x physical cores about optimal for my problems - using more than that saturates memory bandwidth and just generates extra heat without any increase in performance.
I'm using the Matlab Optimisation toolbox to create and solve an optimisation problem which I have called chargeprob. After running my code successfully, I want to implement a maximum calculation time. options = optimoptions("linprog","MaxTime",5) [sol,fval,exitflag,output] = solve(chargeprob,'Options',options) If my understanding is correct this should mean that if the solve takes longer than 5 seconds, the solver should exit saying no solution was found in time. Instead what happens is that it appears to have no effect with the solver taking in this case 30 seconds. What is the correct way to set a timeout on my solver?
This is actually a limitation of MATPOWER. The standard power flow (`runpf`) can handle fixed generation but doesn't enforce branch limits, while OPF (`runopf`) enforces branch limits but allows generation to vary. You could try to approximate using `runopf` with very tight generator limits, this usually worked in my cases when I had to do analysis. Tho, you may have convergence issues due to the very tight constraints and it might still allow tiny variations in generator output, depending on the values you use.
If you delete the peak and fit a polynomial to the baseline then you might stand a chance of having a problem that it can solve, but there is no way it can hope to fit a sharp peak like that. Try fitting a baseline polynomial curve to 100-750 and 1250-4500 then use that baseline to isolate your peak (and use the lowest order you can get a decent fit with). It also helps to have a decent model of a theoretical ideal peak for a peak fitting code to use.
You might have to use pol2cart to convert from polar to cartesian coordinates, which opens up more of the standard plotting functions like patch Example input: theta = linspace(0,pi,2000); r1 = 3 * sin(theta); r2 = 1 + sin(theta); Plotting code: [x1,y1] = pol2cart( theta, r1 ); [x2,y2] = pol2cart( theta, r2 ); figure; hold on; patch([x1 fliplr(x2)], [y1 fliplr(y2)], [0.7,0.9,0.9], 'displayname', 'fill', 'linestyle', 'none') plot( x1, y1, 'r', 'linewidth', 2, 'displayname', 'r1' ); plot( x2, y2, 'b', 'linewidth', 2, 'displayname', 'r2' ); legend( 'show' ); Note if you go past pi for theta then the definition of which region is between the lines gets a little ambiguous, but from here you have all the coordinates to define the fill boundary and the ability to calculate them differently.
I have a MRI image of a brain, made of 25 slices, in NIFTI format (so one file containing the 3D data). I need it to have 30 slices to use a specific medical tool - how can I use interpolation to add intermediate slices (or even just slices at the end) ? I have seen the Matlab function "interp3" mentionned and I tried with the following code: [rows,cols,slices] = size('subject.nii') [x1,y1,z1] = meshgrid(1:cols, 1:rows, 1:slices) [x2,y2,z2] = meshgrid(1:cols, 1:rows, 0.5:0.5:slices) out = interp3(x1, y1, z1, 'subject.nii', x2, y2, z2, 'linear', 0) However, it returns the following error: Error using griddedInterpolant Sample values must be of type double or single. Error in interp3 (line 132) F = griddedInterpolant({X, Y, Z}, V, method,extrap); How can I fix this? Or should I use a different function? I have also seen "imresize" in this forum but I can't figure out how to use it...
This assumes that there actually **is** a 3rd instance for each timestamp, which may or may not be true. Honestly, I'd rather iterate through the list.
MATLAB: Corr Function not working for Spearman
Calling this merely visualization is an understatement IMO. In general, usually what you are interested when inspecting a signal's Fourier transform, is interesting peaks in it's spectrum, and there it would also be natural if it would have been ordered from `-1/dx` to `1/dx`.. The purpose of my question is to get examples of cases where it is natural to view or perform calculations upon the output of `fft` when it is ordered in it's current, natural order.
How to fill a subfield based on conditions in Matlab
I'm translating a code from MATLAB to Julia and noticed differences in the results of the Cholesky decomposition, despite using the same input matrix. In Julia, I used: R = sparse(cholesky(K[perm, perm]).L)' In MATLAB, I used: R = sparse(chol(K(perm, perm))); However, nnz(R) in Julia is 1404, while in MATLAB, nnz(R) is 1352. Exporting R from Julia to MATLAB gives nnz(Rjulia) = 1356. Could this be due to numerical precision differences? How can I ensure consistent results between both environments? K[perm, perm]= https://justpaste.it/gxful
Printing out coordinates of clicked points while user draws polyline in Matlab App Designer
There are an estimated 10^80 atoms in the universe (plus minus 10 or 20 orders of magnitude), so yes, 10^(2^32) is a ridiculously large number.
What is the problem and show the code and how you did it
I'm working on plotting the Power Spectral Density (PSD) in MATLAB using loglog but I'm encountering an issue with the DC component (frequency = 0). Since log_10(0)= -inf MATLAB automatically excludes the DC component from the plot. I tried assigning a small positive value to the DC frequency, and it works to include the component in the plot. However, this approach alters the true frequency values, which I want to avoid because it doesn't align with the actual spectrum. I also considered the "log-of-x-plus-one" transformation but it changes the real frequency axis and doesn’t reflect the true nature of the spectral data. My questions are: What are best practices for including the DC component in log-log spectral plots in MATLAB? Is there a way to represent the DC component (f=0) visually without assigning an arbitrary value that distorts the frequency axis? If the DC component is typically excluded, what’s the standard way to present or annotate it in such plots? Any advice or insight on this would be greatly appreciated! [PSD_u_mean, f_u_mean] = pwelch(detrend(nanmean(u,2)), hanning(WL), floor(WL/2), WL, FS); %% figure; loglog(f_u_mean, PSD_u_mean, 'LineWidth', 1.5); hold on loglog( PSD_u_mean, 'LineWidth', 1.5); xlabel(' frequency') ylabel(' PSD') legend('With Correct Frequency', 'Using Indices Instead of Frequency');
Creating internal hyperlinked table of contents through the Word COM in Matlab
Error in calculating the average values of the rows of a group of excel-files
Thank you for your comment Cris Luengo. I will try to create minimal reproducible example hereafter. I have found problem finally. lambda optimization pars lambda=lambda*10 and lambda=lambda/10 are stuck and the algorithm repeatedly increase and decrease the lambda. I have changed the code "test_error_norm <= errors_of_epochs(epoch_number,1)" to "test_error_norm <= errors_of_epochs(epoch_number,1)*0.80" and prevent the unnecessary repeated change. Looks like lambda change should be done carefully.
I have a matlab toolbox, with a single-window GUI. I was able to build it mcc/deploytool to create a standalone 7MB executable. However, I was not happy for the installer size, as the R2016 matlab runtime is 700MB in size, 100x larger than my application. When I saw a new matlab compiler API compiler.runtime.customInstaller coming with R2024b is cable of creating smaller MCR installer including only needed files, I was very happy and immediately tried it, however, the result was disappointing. The installer bundled with MCR in R2024b for my app build by deploytool - without using the customInstaller - is 1.2GB in size (another 2x increase in size compared to the already large package generated by R2016). Then, when I called results = compiler.build.standaloneApplication("myapp.m"); compiler.runtime.customInstaller("myapp_installer", results, 'RuntimeDelivery', 'installer'); however, the generated package has the same 1.2GB in size. I have followed the help page of compiler.runtime.customInstaller https://www.mathworks.com/help/compiler/compiler.runtime.custominstaller.html did I miss anything? why customInstaller fails to trim the installer size? my app only use basic matlab features. the requiredMCRProducts.txt file shows that I only need the following MCR components 'MATLAB Runtime - Core' 'MATLAB Runtime - Graphics' 'MATLAB Runtime - Non Interactive MATLAB' 'MATLAB Runtime - Numerics' 'MATLAB Runtime - Image Processing Toolbox Addin'
I am trying to implement levenberg marquardt algorithm in matlab but my code doesn't converge and errors keep getting bigger and bigger after first iteration. I checked jacobian table, inverse function and so on but I couldn't figure it out what is the problem. I look for the jacobian and calculated both by using numerical differentiation and by calculating partial derivative formulas and calculating by matrix operations. I tried build in inverse function and cholesky factorization I calculated the matrix and bias calculation, done in the code, with Excel table and formulas and checked the values. Code find a low residual error at first bu after calculating jacobian and finding the delta_value and changing the weights in second or third iteration the norm of residuals getting bigger and bigger. Is there anything that I can't see? clear; clc; % Define hyperparameters epoch = 10; % Maximum number of epochs tol = 0.02; % Tolerance for convergence lambda = 0.01; % Initial regularization parameter layer_number = 3; % number of layer(input and output are included) input_size= 1; % Number of input features hidden_size = 15; % Number of neurons in the hidden layer output_size = 1; % Number of outputs num_runs = 5; % Number of runs to calculate average number_of_sample=46; % Number of sample % Create training data for problem one Sinus wave y = 1/2 + 1/4sin(37pix) input_vals = linspace(-1, 1, number_of_sample)'; % 40 inputs scattered in the interval [-1, 1] target_vals = 0.5 + 0.25 * sin(3 * pi * input_vals); % Target output according to given formula % Run the algorithm 5 times for calculating average error to create plot errors_of_epochs_for_average_5_run = zeros(epoch,1); for run = 1:num_runs W1 = rand(hidden_size,input_size); b1 = rand(hidden_size,1); W2 = rand(output_size,hidden_size); b2 = rand(output_size,1); parameterVector= [W1(:);b1(:);W2(:);b2]; %parameter vector for jacobian matrix; errors_of_epochs = zeros(epoch,1); % to store error values of each epoch for epoch_number = 1:epoch % Initialize matrix to store error vectors for each run output_vals=zeros(number_of_sample,output_size); %outputs for all samples errors_for_each=zeros(number_of_sample,output_size); %error values for each input output value %forwardpass loop for i=1:number_of_sample output_vals(i,output_size) = forward_pass(input_vals(i,input_size), W1, b1, W2, b2); end errors_for_each = target_vals - output_vals; error_norm = norm(errors_for_each); errors_of_epochs(epoch_number,1) = error_norm; % calculate average sum of square for each epoch ***parameterVector= [W1(:);b1(:);W2(:);b2]; % recreate paramVector with new weights*** Jaco=jacobian(parameterVector, target_vals, input_vals,hidden_size); % calculate jacobian while true % to calculate delta again when error is bigger than previous one JTJ=Jaco'*Jaco; I=eye(size(JTJ)); JTJ_Lambda_Eye=JTJ+lambda*I; JTe=Jaco'*errors_for_each; try [R,Flag]=chol(JTJ_Lambda_Eye); if Flag disp('Matrix must be symmetric and positive definite.'); end % JTJLEyeInverse=inv(JTJ_Lambda_Eye); L = chol(JTJ_Lambda_Eye, 'lower'); n=size(JTJ_Lambda_Eye,1); I=eye(n); Y=zeros(n); % Solve for Y using forward substitution for i = 1:n Y(:, i) = L \ I(:, i); end % Now solve L^T * X = Y for X JTJLEyeInverse = L' \ Y; catch disp('Cholesky factorization failed.'); break; end deltaValue=JTJLEyeInverse*JTe; parameterVectorTest=parameterVector; parameterVectorTest=parameterVectorTest-deltaValue; % check wheather the new error create better value. W1_test = reshape(parameterVectorTest(1:hidden_size * input_size), hidden_size, input_size); b1_test = reshape(parameterVectorTest(hidden_size * input_size + 1:hidden_size * input_size + hidden_size),hidden_size, input_size); W2_test = reshape(parameterVectorTest(hidden_size * input_size + hidden_size + 1:end - 1), output_size, hidden_size); b2_test = parameterVectorTest(end); %test delta value whether they are too small for change or not if norm(deltaValue)<tol; disp("Parameter changes are too small to continue"); break; end %test feedforward test_output_vals=zeros(number_of_sample,output_size); for i=1:number_of_sample test_output_vals(i,output_size) = forward_pass(input_vals(i,input_size), W1_test, b1_test, W2_test, b2_test); end test_errors_for_each = target_vals - test_output_vals; test_error_norm = norm(test_errors_for_each); if test_error_norm > errors_of_epochs(epoch_number,1) lambda=lambda*10; % if lambda>1000 % lambda=1000; % end else break; end end %finis point of bigger error and increasing lambda if test_error_norm <= errors_of_epochs(epoch_number,1) W1=W1_test; b1=b1_test; W2=W2_test; b2=b2_test; lambda=max(lambda/10, 1e-7); end if test_error_norm <= tol disp(['Converged at epoch ', num2str(epoch_number), ' in run ', num2str(run)]); break; end end errors_of_epochs_for_average_5_run = errors_of_epochs_for_average_5_run + errors_of_epochs; %to calculate average of 5 run end % Plotting the result for investigating % Calculate the average error across all runs avg_epoch_errors = mean(errors_of_epochs_for_average_5_run, 1); % Plot average error vs. epochs plot_target=zeros(number_of_sample ,1); for i_test = 1:input_size X_test = input_vals(i_test); % Forward pass to get the current output plot_target(i_test) = forward_pass(X_test, W1, b1, W2, b2); % Calculate the current error end figure; hold on; %plot(1:biggest_last_epoch_number, avg_epoch_errors(1:biggest_last_epoch_number), '-o'); plot(input_vals, target_vals, 'r-o'); plot(input_vals, plot_target, 'b-o'); xlabel('Epoch'); ylabel('Average Error'); title('Average Error per Epoch across 5 Runs'); grid on; hold off; % Define forward pass function function [outputf,A1] = forward_pass(X, W1, b1, W2, b2) Z1 = (W1 * X) + b1; % Linear combination for hidden layer A1 = sigmoid(Z1); % Sigmoid activation for hidden layer Z2 = (W2 * A1) + b2; % Linear combination for output layer outputf = Z2; % Output layer end % Sigmoid activation function function cikti = sigmoid(x) cikti = 1 ./ (1 + exp(-x)); end % Derivative of the sigmoid function function cikti = sigmoidDerivative(x) cikti = sigmoid(x) .* (1 - sigmoid(x)); end % Define function for calculating Jacobian function jaco_return=jacobian(jparameterVector, jtarget_vals, jinput_vals,jhidden_size) jaco_return=zeros(length(jtarget_vals), length(jparameterVector)); W1 = reshape(jparameterVector(1:jhidden_size * 1), jhidden_size, 1); b1 = reshape(jparameterVector(jhidden_size * 1 + 1:jhidden_size * 1 + jhidden_size),jhidden_size, 1); W2 = reshape(jparameterVector(jhidden_size * 1 + jhidden_size + 1:end - 1), 1, jhidden_size); b2 = jparameterVector(end); for i=1:length(jtarget_vals) % to creat each line of jacobian for each input output pair [~ , jA1] = forward_pass(jinput_vals(i),W1,b1,W2,b2); derivW1 = -1 * W2'.* sigmoidDerivative(jA1) *jinput_vals(i); %W1 partial derivatives derivb1 = -1 * W2'.* sigmoidDerivative(jA1); %b1 partial derivatives derivW2 = -1 * jA1; %W2 partial derivatives derivb2 = -1; %b2 partial derivatives linear activation function jaco_return(i,:)= [derivW1(:);derivb1(:);derivW2(:);derivb2]; %each line of jacobian matrix end epsilon=1e-10; jaco_test=zeros(length(jtarget_vals), length(jparameterVector)); jparameterVector_pus=jparameterVector; for jsatir=1:length(jtarget_vals) for jsutun=1:length(jparameterVector) outpus_test_normal=forward_pass(jinput_vals(jsatir),W1,b1,W2,b2); jparameterVector_pus(jsutun)=jparameterVector(jsutun)+epsilon; W1_test = reshape(jparameterVector_pus(1:jhidden_size * 1), jhidden_size, 1); b1_test = reshape(jparameterVector_pus(jhidden_size * 1 + 1:jhidden_size * 1 + jhidden_size),jhidden_size, 1); W2_test = reshape(jparameterVector_pus(jhidden_size * 1 + jhidden_size + 1:end - 1), 1, jhidden_size); b2_test = jparameterVector_pus(end); jparameterVector_pus(jsutun)=jparameterVector(jsutun); output_vals_test_plus = forward_pass(jinput_vals(jsatir),W1_test,b1_test,W2_test,b2_test); jaco_test(jsatir, jsutun)=((output_vals_test_plus- outpus_test_normal)/epsilon)*-1; end end jaco_return=jaco_test; end
Since you’re summing over the 3rd and 4th dimension after the loop, I would recommend you do that inside the loop and directly build the desired 2D output. Unless the code you posted is not representative and you actually need the 4D output of course.
You're right; I apologize for the inconvenience. I have uploaded the Excel file.
It does not answer the original question but compiling and running the exe with Matlab 2023a, .NET is not *loaded* by default so it is possbile to change to .NET core.
I am trying to patch a color gradient of given angular data Here is the data: n = [263.6909 287.9987 262.1933 199.6890 128.5683 71.1718 34.6535 15.2568 6.2683 2.4868 0.9872 0.4063 0.1793 0.0876 0.0487 0.0315 0.0241 0.0221 0.0243 0.0319 0.0495 0.0895 0.1838 0.4174 1.0159 2.5605 6.4504 15.6740 35.5053 72.6566 130.6707 201.9328]; theta=0:(2*pi/32):(2*pi*(32-1)/32); theta(theta&gt;pi) = theta(theta&gt;pi)-2*pi; I use a patch command figure hold on patch(cos(theta), sin(theta), n, 'EdgeColor', 'none'); quiver(0,0,-4.6492,-0.9099,0.5,'k','linewidth',3); axis equal ** edit start 3/12/2024 ** The gradient is suppose to be perpendicular to the line between the peak of the concentration and the opposite point along the rim (i.e, from $\theta(n_{max})$ and $\theta(n_{max}+\pi)). There are two options I'm trying to apply: 1.Assuming that there is an exponential decaying gradient where the gradient patch decays from n_max to zero in the vertical direction. fitting a Gaussian to the data and use that with a corresponding theta which is segmented equally with respect to the location of the peak (i.e, one of the array point of theta is exactly where the peak is). ** edit end 3/12/2024 ** Here in the plot below is what I obtain, and what I wish to obtain I highlight that the data is part of a dynamical simulation where the array n changes every iteration, and therefore the gradient slope, and direction, must be according to the given n
there are different ways to add slices. interpolation is definitely not the easiest. Firstly, one tool I really like for reading and writing NIfTI files is Tools for NIfTI and ANALYZE image by Jimmi Shen. It may look a bit old-fashioned compared to the built-in matlab function but I think it gives you a bit more control over the header and the pixel data. If you use that toolbox and do nii = load_untouch_nii ( '/tmp/MNI152_T1_2mm.nii.gz' ); then you will have a struct nii with header field hdr and the image field (the pixels) img. This example image has size 91x109x91, you can use interp to sample it to (say) 100x150x100 points: [ gx, gy, gz ] = ndgrid ( 1:150, 1:100, 1:100 ); img2 = interp3 ( nii.img, gx, gy, gz, 'nearest' ); and you can look at the two images: figure ( 1 ); imagesc ( nii.img ( :, :, 1 ) ); axis equal figure ( 2 ); imagesc ( rot90 ( img2 ( :, :, 1 ) ) ); axis equal you can see that the image itself has not changed - you have just added empty space at the sides. (you could have done this by just expanding the matrix!) You can also resample your image so that the new image fills the same amount of world space as the old image (in your example only in the z-direction, but x and y is also possible): [ gx, gy, gz ] = ndgrid ( linspace ( 1, 109, 150 ), linspace ( 1, 91, 100 ), linspace ( 1, 91, 100 ) ); img3 = interp3 ( double ( nii.img ), gx, gy, gz, 'linear' ); figure ( 3 ); imagesc ( rot90 ( img3 ( :, :, 1 ) ) ); axis equal The reason that img3 may not be such a good idea is that you have changed the world-size of the image: the original field nii.hdr has a field pixdim which gives the spacing of every point (in this case it is 2x2x2 mm³). But now that you compress the same world-space into more points, their spacing has decreased; you now need to change the header of your resampled file to reflect that (i.e., the world size of your pixels needs to be smaller). Long story short, img2 really has slices added to it, img3 has been spread over more slices.
I try to convert a matlab script using spectrogram function to the matplot lib spectrum function. Once converted to a spectrogram grey image, the output images are similar but the Power spectral density matrix shape are different Matlab code: [~,~,~,P] = spectrogram(X, Fs/N, 0, N, Fs, 'centered'); with: spectrogram(x,window,noverlap,nfft,spectrumtype) Fs = 50 * 10**6 nfft = 500 In that case the shape of P is 500 x 500 Python code: P, freq , t, img = plt.specgram(x, NFFT=nfft , Fs=Fs, Fc=Fc, noverlap=0, window = np.hanning(nfft )) In that case the shape of P is 500 x 100000 Looks like the window parameters from matlab allows to divide the signal into segments and has nothing to do with the window parameter of plt.specgram (as per the documentation actually ;) ) My question is: how to produce a 500x500 matrix using plt.specgram ? Any idea ? Thank you !
How to add slices to a MRI image? (interpolation)
enter image description hereenter image description here I am working on the IEEE 34-bus distribution network using MATLAB Simulink. I am using the system provided in the link below: "https://www.mathworks.com/matlabcentral/fileexchange/123220-ieee-34-bus-distribution-feeder-discrete-simulink-model?s_tid=srchtitle_support_results_1_ieee%2034" When I try to perform load flow analysis for the model, the results appear to get stuck at the bus associated with the voltage regulator. As a result, I cannot obtain load flow results for all the buses. What might be causing the issue with the voltage regulator in the simulation? Are there any specific settings or adjustments required for the voltage regulator to enable successful load flow analysis? Any guidance or suggestions to resolve this issue would be greatly appreciated.
Thank you so much! I just got it working! I'm just a student, and this is our first semester using Simulink, so I didn't even know that some of these blocks existed.
@CrisLuengo From what I understand, all of the rows labeled `202211` in column 1 are assigned to be aggregated type **1**, except for the **third** instance, which is assigned to type **2**. Similarly for rows labeled `202212`, and so on.
I have a large Simulink model consisting of several subsystems, piping sections for example. Each subsystem is modeled with a m-function. Within the m-function I throw warnings (for now I use matlab warnings but I could only print the information) when specific conditions occur in the pipings. I would like to trace the warning message to the full path of the block calling the m-function, in order to inform the user of which piping is causing the trouble. I have tried using gcb in my m-functions but it is not supported by the code generation capabilities of Simulink, which I need. Is there another approach to get the whole trace of a warning in this use case ?
MATLAB unittest: set variable and use it across all test method in one test class
I am trying to find a way to tune the parameters of controllers with variable structure for power systems using Matlab and simulink. I would like to find a method where it is not needed to simulate the environment to tune the parameters. For now I use the minimization of the H2 or the H-infinity norm of the system. I am currently trying to tune the parameters of a simple PID controller for a second order plant (G(s) = 1 / (s^2 + 10s + 20)). The model is depicted below : model I have tried to use particle swarm optimization to minimize H2 or H-infinity norm of the transfer function : T(s) = G(s) / (1 + C(s)G(s)) where G(s) is the transfer function of the plant and C(s) = Kp + Ki/s + Kd*s The problem that I have is that the optimization return very large parameters (the order of magnitude of the gains is between 10^10 and 10^14) that lead to a non-ideal behvior. For comparison this is the resulting behavior when optimizing with the norms: norm And this is the resulting behavior when optimizing with simulation : simulation The value of the H2 and H-infinity norms with the resulting parameters are very low while the resulting behavior is really oscillatory. Thank you,
Matlab object arrays' method call equivalent in Python
There are many solutions for your immediate problem, but in general you cannot translate syntax 1-to-1 from one language to another. Each language has its own syntax and its own peculiarities. In MATLAB, A.toClass2() and toClass2(A) both call the same function. The second syntax you can directly translate to Python by writing a free function (i.e. not a class method) that does something different depending on the type of the input. A different alternative is to not create lists of your object in Python, but to have an object contain a list with the data (or create a class that contains a list of your objects). Then you can customize methods working on that object.
I generate a Simulink model programmatically which means that I change the name of the signals at bus selector inports. In order to reconfigure the bus selector after programmatically changing the model I get all input signals from the Bus Selector block, join the signal names and provide them again to the Bus Selector output : list_input_signals = get_param(bus_selector_handle,'InputSignals'); input_signals_str = strjoin(list_input_signals , ','); set_param(bus_selector_handle,'OutputSignals',input_signals_str ) This is based on an answer on Mathwork's forum here : https://fr.mathworks.com/matlabcentral/answers/772493-select-bus-elements-programmatically It works but the get_param instruction is painfully slow. It is taking up 99% of the execution time of the three lines according to Matlab's profiler. It represents around 15s for 250 bus selector blocks and it scales too much for bigger models. Is there a more efficient way to refresh the Bus Selector block or to access all input signals to replace the incrimated get_param ? I tried the following workaround but with the same issue : ph = get_param(bus_selector_handle, 'PortHandles'); sh = get_param(ph.Inport, 'SignalHierarchy'); input_signals_str = strjoin({sh.Children.SignalName},','); set_param(bus_selector_handle,'OutputSignals',input_signals_str )
I have a Matlab file containing an array of datetime objects with 18750 timestamps. When I use scipy.io to import the data, it gives the following output which is very different. I am expecting an array of timestamps just like what is seen in Matlab. Any idea how I can achieve this? Thank you very much for your time and attention.
I'm trying to locate the file in the Matlab installation or per-user configuration in which the path to the Java JDK is stored. I tried changing the JDK path via jenv and then looking for a recently-modified file (via find . -type f -mtime -1) but the only files found by that test do not seem to contain the Java JDK path. The bigger picture is that I am running Matlab in a Docker container (see this web page about that) and I am trying to create a persistent configuration for the Java JDK. I can change the JDK location via jenv when Matlab is running in a Docker container, but that change is forgotten after exiting and relaunching Matlab.
How MATLAB makes the distinction between P-Cores and E-Cores?
I'm new to Matlab and I'm trying to write a code that draws these two curves in polar coordinate system and colors the area bounded by them. r1 = 3 * sin(theta) r2 = 1 + sin(theta) I've tried several preliminary methods, but to no avail. I'm using Matlab R2022b
The only time you need to apply `fftshift` is for visualization. Somehow people prefer to look at the frequency range -N/2 to N/2 rather than 0 to N-1. But this is just our preference, any computations you do are not concerned with this. Don’t think of `fftshift` as rearranging the FFT output, but rather as shifting the window over which we look at the periodic frequency domain.
@jarhead The data you presented doesn't represent a smooth gradient in any direction - do you want us to infer the vector angle from the data and then generate the gradient? Or smooth out the vector `n` via interpolation? Or can you just return the vector direction from whatever process makes `n`? It's not clear from your question where you got `-4.6492,-0.9099` from for the quiver...
@ShivamMishra the OP of the other post is mistaken, he also has a TimeStamp object
Please define clearly what you mean by "It gives wrong result", you should provide a [mre] with input and output data for this function only, if that is where you think the error is.
Thanks, I just discovered that. You should have written that as an answer.
@CrisLuengo This case is a bit simpler because there is only one color per column in the sample image. Kostas, your image doesn't seem to have an alpha channel. How did you want to handle that?
Thank you for this comment. I'm editing my question now. In principle, the axis of polarization (indicated by the vector, black arrow) is not necessarily identical to the direction of the gradient. So perhaps what that I am asking here is why the patching of the gradient (given the distribution along the rim is not symmetric). I thing the problem lies with the fact that the data I have is not symmetric around the angle segmentation, but even if I interpolate and take N to be very large (such that the intervals between the angles is small) I still obtain a messed-up color patch.
I just discovered, that there is also a hybrid method, which is basically a multistep-Runge-Kutta (called Runge-Kutta-Nyström). As I understand it, it needs N ode-evals to achieve order N (maybe +/- 1). But it should be more stable than the Adams-methods at higher stepsizes. Can someone tell me, what increase in stepsize one can expect (if that is possible)? Say I do 5 ode-evals/order 5. Stability aside, RKN would have to permit a 5 times bigger stepsize to compete with Adams efficiency-wise...
I have a data set, FR. I am trying to plot the confidence levels for the same but I am encountering a warning message :"Warning: Equation is badly conditioned. Remove repeated data points or try centering and scaling.". I don't know what is the issue as well as how to solve it. Any kind of help will be very useful. I am getting a graph like this (as shown below) but I think this enter image description here %Create fit and confidence interval FitVec = fit(freq_tl,T121,'poly9') pRvecConf = predint(FitVec,freq_tl,0.95,'observation','off'); %get the fitting values fitY=feval(FitVec,freq_tl); %multiply the confidence interval with sqrt(xVec(i)).^2 .*xVec' ci=(fitY-pRvecConf(:,1)); %get the weighted confidence interval Conf_new=[fitY-ci,fitY+ci]; %Plot figure plot(FitVec,freq_tl,T121) hold on plot(freq_tl,Conf_new,'m--') legend('Data','Fitted curve','Confidence','Location','se') xlabel('Length') ylabel('Strength')
It could be, but i'd like to rather keep 1 check (obj creation, obj creation inside it, obj deletion from it, obj deletion) per the lowest test level. I assume, function with testCase parameter is the lowest here, and there are no subtests or substeps or something like this? Except global variables, the idea is to read id as input parameter and then add some teardown-like method, that will update input parameters with any test data that is created by passed test, so then next one can use setup with updated data to use them
Matlab mldivide returns NaN when there are multiple solutions
How to Run Compiled MATLAB Executable Without MATLAB Installed?
compiler.runtime.customInstaller fails to reduce mcr installer size
...*Without* the backslash-h, I get hyperlinks from the *page numbers in the TOC* to the headings when working in Word, but not when exported to PDF. I suspect that this property is described as having an effect when the document is "saved to the Web" (i.e.HTML) and that may have had an effect at one time. Not sure it does now, but it may be affected by other "save to web" settings.
I'm trying to install MATLAB 2024a on a Ubuntu 22.04 LTS system. The system is behind a proxy which requires configuring a proxy and adding a CA Certificate. For whatever reason, MATLAB does not seem to use the system's certificate store. There is a place where I can configure a proxy but I cannot find anywhere where I can add/configure a certificate. Therefore, when I click "test connection", it will fail. When I try anything that accesses the internet (documentation, install addon, etc), I get a certificate error. I contacted support and they tell me they don't support that or any SSL interception. They tell me to use offline installers and manually goto mathworks for documentation. I find this hard to believe that all the corporations around the world that have proxies that require a certificate are doing this with MATLAB. Also, on the windows computers (behind the same proxy), it works fine. Googling, I found an old solution of using keytool to add to the java keystore but that doesnt seem to work anymore. Does anyone know of a way to resolve this? For example, firefox does its own thing but has a plugin to make it work.
As I understand it, in this function the power generation of the generators is not fixed. But I want to pass a fixed power generation and see, if there's a power flow possible (adhering to the branch limits) with the given settings. Is Matpower not able to do that?
Less than 10 minutes after posting this I was able to finally detect the source of the weird error: for some reason, and only on certain loop conditions, MATLAB would report a number in the cell yp with some numerical round-off, reporting it as 35.0 for example instead of 35. This would cause the hygepdf to return a null value, because it can only work with integers, hence the screw up. The solution was to use a rounding function on yp, and this line fixed it: yv{j} = round(yp(fin)); I'll leave this up here in case anyone else has similar problems, but cannot explain why it only had those round up errors with certain loop iterations and not with others!
MATLAB Programmatic App Fcn Callback not working
@Wolfie I added two photos , If you need more explanation ,you can tell me
@CrisLuengo For my purposes, I don't need the output of the loop calculation results. All individual wave harmonics are calculated in the loop. Accordingly, they depend on four variables: frequency, angle of direction and two coordinates - therefore, the array is four-dimensional. To get the final desired result - a surface waving, I perform a double summation of the frequencies and angles of all harmonics. However, I have not figured out how to do as you advised. Do the summation through a loop, thereby adding another outer loop in addition to the main one? Or something else?
Thank you for your response. I tried this code because the use of GPU is separate in the matlab fft2 code description. If I use GPU instead of CPU when processing large-capacity images, wouldn't it be faster? I tried it with the thought, but I didn't know that there would be a small difference in speed between CPU FFT and GPU FFT. Thank you for the good insight.
Thanks to beaker's advices I was able to devise this: inputs: Map: Matrix containing label values. Can be double, int, char. K: Maximum count of values for colormap(). Chosen to match K-colour algorithm below. Distance: Diameter of neighbourhood scanning for adjacent regions. 0. ensure the label are consistent Labels = unique(Map); for ii = 1 : N Map(Map == Labels(ii)) = ii; end 1. Matrix to Graph Preallocate adjacency matrix. Loop over all "grains" dilate them (to overflow to their neighbours). Exclude 0 from the list (Labels outside the neighbourgood are zeroed). Fill row in adjacency matrix. Finally zero diagonal in the matrix - eliminate self-adjacency. Graph = false(N); for ii = 1:N Grain = imdilate(Map == ii, strel('disk', Distance)); Neighbours = unique(Map .* Grain); Neighbours = Neighbours(Neighbours ~= 0); Graph(Neighbours, ii) = true; Graph(ii, Neighbours) = true; end Graph = Graph & ~eye(size(Graph)) 2. Use modified Kempe's K-colour algorithm 2.1. Preallocate working variables Preallocate Stack variable to keep trace of nodes removed form the graph, Pruned to keep 'pruned' graph, Pool to keep 'active' nodes and Codes to store 'Colour codes'. N = numel(Labels); Stack = nan(N, 1); Pruned = Graph; Pool = 1 : N; Codes = nan(1, N); 2.2. Dismantle the graph Find node with least neighbours, put its index on stack and delete it from adjacency matrix (prune it). Repeat with pruned adjacency matrix until last node is on the stack and adjacency matrix is empty. for ii = 1 : N Degrees = sum(Pruned); [~, idmin] = find(Degrees == min(Degrees), 1); [~, Pruned] = pop(Pruned, idmin); Stack(ii) = Pool(idmin); [~, Pool] = pop(Pool, idmin); end 2.3. ('Reassenble' the graph) and assign codes for ii = N : -1 : 1 % Start with last node in the stack % Read colour codes of neighbouring nodes. `NaN` returned for nodes still on stack* NgbCodes = Codes(Graph(Stack(ii), :)); % Check count of codes used in neighbouring nodes. if sum(~isnan(unique(K))) < Ncolours % If lower than number of codes, find the unused codes ColorPool = setdiff(CodeList, NgbCodes); % Assign the first unused code to the node Codes(Stack(ii)) = ColorPool(1); else % If all codes are used, leave unassigned (let user increase K and try again) end end 3. Apply the codes to the matrix Map = Codes(Map); Nested functions Both functions pop rc-th element, or column, respectively, from matrix or vector. function [CLMN, B] = prune(A, rc) CLMN = A(:, rc); B = A([1 : rc - 1, rc + 1 : end], :); B = B(:, [1 : rc - 1, rc + 1 : end]); end function [Val, B] = pop(A, rc) Val = A(rc); B = A([1 : rc - 1, rc + 1 : end]); end Modifications in the algorithm described in linked presentation, page 9: I do not look for (any) node with Degree D < K, I look for node with lowest degree (no matter how related to K). If D < K is valid for at least one node, it is found. If such node does not exist (easy for K=3) the branches do not differ significantly. I don't use recursive call, stack and other variable sizes are determined in the beginning and they only shrink. Condition for neighbouring colour codes assigned count NC < K is automatically true for D < K - no need for such check then.
Matlab Warning: Equation is badly conditioned. Remove repeated data points or try centering and scaling
Can you produce maybe a small example with code that demonstrates the issue and post that? It is hard to advise you unless we see exactly how you scaled the problem and how large the differences are and how fast they are growing.
@beaker it's not particularly nice looking or efficient, but you can get the run-lengths with `arrayfun(@(x)1+x-find([NaN,m(1:x)]~=m(x),1,'last'),1:numel(m));` to replace that loop. Albeit arrayfun is basically a loop anyway...
I've developed simulink model like below: In the model there is slider gain which can be adjusted in range from 0 to 1. I'd like to update Scope: when slider gain is adjusted: I've watched the video where it worked by default. Lecturer just set up in Scopes options, Time range from 0 to 0.04 and it did update. In my model it doesn't work. How to achieve such reactive simulation?
I need help coding Direct Sequence Spread Spectrum into my Binary Phase Shift Keying Code. DSSS is the main piece of my objective. The code provided is composed of Binary Information, Carrier Wave, BPSK, AWGN, Impulse Noise. clc; clear all; close all; N = 7; I = randi([1], 1, N); I = [1 0 1 0 1]; for V = 1:length(I) %Binary Phase if I(V) == 1 nn(V) = 1; else nn(V) = -1; end end i = 1; t = 0:0.0001:length(I); for j = 1:length(t) if t(j) &lt;= i y(j) = nn(i); else i = i + 1; end end Fc = sin(2 * pi * 2 * t); x = y .* Fc; % AWGN Noise SNRdB = 10; % Adjust SNR as needed snr_lin = 10^(SNRdB / 10); noise_variance = 1 / snr_lin; noise = randn(size(t)) * sqrt(noise_variance); AWGN = x + noise; % Impulse Noise Parameters impulse_amplitude = 10; % Adjust the amplitude as needed impulse_prob = 0.01; % Probability of an impulse at each time index impulse_noise = zeros(size(t)); impulse_indices = rand(size(t)) &lt; impulse_prob; impulse_noise(impulse_indices) = impulse_amplitude; IMPULSE = x + impulse_noise; subplot(5, 1, 1); plot(t, y); axis([0, length(I), -2, 2]); xlabel('Time'); ylabel('Voltage') title('Transmitted Binary Information'); subplot(5, 1, 2); plot(t, Fc); axis([0, length(I), -2, 2]); xlabel('Time'); ylabel('Voltage'); title('Carrier Signal'); subplot(5, 1, 3); plot(t, x); axis([0, length(I), -2, 2]); xlabel('Time'); ylabel('Voltage'); title('BPSK'); subplot(5, 1, 4); plot(t, AWGN); axis([0, length(I), -2, 2]); xlabel('Time'); ylabel('Voltage'); title('BPSK with AWGN Noise'); subplot(5, 1, 5); plot(t, IMPULSE); axis([0, length(I), -2, 2]); xlabel('Time'); ylabel('Voltage'); title('BPSK with Impulse Noise'); BPSK PLOT IMAGE I did try to code DSSS into the BPSK code along with the AWGN and Impulse Noise but results got errors, and no visible outputs in its plots or graphs.
I generated filter coefficients with scipy's signal.butter to use in real time filtering in Arduino, and I'm validating the filter with a simple Matlab code that produces a dummy wave and produces a filtered wave from it. I validated the scipy generated coefficients for a 1st order filter, but when doing 4th order the filter seems to become unstable, which makes no sense. I think it's a logic issue either on the math side, or the interpreting the coefficients side, but maybe it's a code issue. Scipy generates 9 denominators (a0 to a8) and 5 numerators (I'm assuuming b0 to b4) but the matrix for b has the following format: [ 4.82121714e-13 0.00000000e+00 -1.92848686e-12 0.00000000e+00 2.89273028e-12 0.00000000e+00 -1.92848686e-12 0.00000000e+00 4.82121714e-13] In the first order validation I simply ignored the 0s, and assumed the third value to be b1, so I've been doing the same, assuming the non-0 values to be b0-b4. When running the code for 1st order the signal gets filtered (commented part of the code), but when doing it for 4th order it explodes (uncommented part of the code). Matlab code % --------- Data Señal de entrada Fs = 20000; % frecuencia de muestreo (o cuantas muestras por segundo) (Hz) T = 1/Fs; % periodo de muestreo (o delta t por muestreo) (s) L = Fs; % Longitud de señal, L=Fs para ser 1 segundo t = (0:L-1).*1/Fs; % vector de tiempo (s) f = 10; % frecuencia señal de entrada (Hz) x = sin(2.*pi.*f.*t) + 0.1*sin(2*pi*1000*t) + 0.1*sin(2*pi*5000*t); % señal de entrada con ruido % -------- cutoff frecuencias, wc = 1/RC = 1/tao; wc = 2*pi*fc = 1/tao fcLPF = 13; fcHPF = f^2/fcLPF; tao1 = 1/(2*pi*fcHPF); tao2 = 1/(2*pi*fcLPF); % -------- coeficientes, Band-pass 4to° orden a0 = 1; % a1 = -1.99832407; % a2 = 0.99833393; a1 = -7.99560326; a2 = 27.96927189; a3 = -55.90796275; a4 = 69.84684949; a5 = -55.84709416; a6 = 27.90840316; a7 = -7.96951656; a8 = 0.99565219; % b0 = 0.00083304; % b1 = -0.00083304; b0 = 4.82121714/10000000000000; b1 = -1.92848686/1000000000000; b2 = 2.89273028/1000000000000; b3 = -1.92848686/1000000000000; b4 = 4.82121714/10000000000000; % ------- Algoritmo filtro Band-pass y = zeros(1,length(t)); for n=9:length(t) y(n) = - a1/a0*y(n-1) - a2/a0*y(n-2) - a3/a0*y(n-3) - a4/a0*y(n-4) - a5/a0*y(n-5) - a6/a0*y(n-6) - a7/a0*y(n-7) - a8/a0*y(n-8) + b0/a0*x(n) + b1/a0*x(n-1) + b2/a0*x(n-2) + b3/a0*x(n-3) + b4/a0*x(n-4); % for n=3:length(t) % y(n) = - a1/a0*y(n-1) - a2/a0*y(n-2) + b0/a0*x(n) + b1/a0*x(n-1); end % ------- figuras figure; hold on plot(t,x,"k") plot(t,y,"r","LineWidth",2) ylabel("Amplitud de Señales") xlabel("Tiempo [seg]") legend("Señal Original","Señal Filtrada") box on hold off I don't think it's an issue, but here's the python code I used, I'm running it on collab import numpy as np import scipy as sp import matplotlib.pyplot as plt from scipy import signal bt,at= sp.signal.butter(4,[7.692307692307693,13],'bandpass',fs=20000) b1,a1= sp.signal.butter(1,[7.692307692307693,13],'bandpass',fs=20000)
This is relevant but doesn't really answer the question of *how*. For example, it doesn't tell us what would happen on a CPU with only E-cores, no P-cores, like Alder Lake N, or Xeon 6 Sierra Forest. Or a VM that had only E cores on a normal desktop. Or if run on hypothetical future machines with different kinds of P and E cores, whether it would still detect the E cores as E cores. (Like on AMD where their Zen4c cores are just Zen4 but with smaller cache and tuned for lower max clock speed.)
Error: Operator '>' is not supported for operands of type 'cell'.
I think the output produced by Matlab is correct. Note that using the numerical version of `rref` (with some number instead of `h`) gives the same result. From [Wikipedia](https://en.wikipedia.org/wiki/Row_echelon_form#Reduced_row_echelon_form): (a) the leading entry in each nonzero row must be `1`; and (b) each column containing a leading `1` must have `0` in all its other entries. According to (a), the leading entry of the second row must be `1`, not `3-2*h`. Also, from (b), entry (1,2) must be `0`, not `h` as you expected
emphasize neighbouring regions in matlab
To add DSSS to your BPSK signal, you have to combine your data signal with a higher data-rate bit sequence (or code). Before you apply the tone you have to multiply your BPSK signal by the code, below I show a code for a chip rate (the ratio between code and data rates) of 10: clc; clear all; close all; N = 7; I = randi([1], 1, N); I = [1 0 1 0 1]; for V = 1:length(I) %Binary Phase if I(V) == 1 nn(V) = 1; else nn(V) = -1; end end i = 1; t = 0:0.0001:length(I); for j = 1:length(t) if t(j) &lt;= i y(j) = nn(i); else i = i + 1; end end %% DSSS M = 10; code = randi([0 1], 1, M); code_nn = code*2-1;% Binary phase % Code length = 1 BPSK symbols code_y = repmat(code_nn, round(length(y)/length(I)/M), 1); code_y = code_y(:).'; code_y = repmat(code_y, 1, length(I)); % DSSS signal y_dsss = y(1:length(code_y)).*code_y; %% Fc = sin(2 * pi * 2 * t); x = y .* Fc; Also, I recommend you to use repmat and similar function to create the Binary phase and the y signal, it will be faster. Just check the way I did for the code signal.
About a `jenv` command in `startup.m`, the difficulty I see is that Matlab always says to restart in order for the changes to take effect, so just putting `jenv` won't make the change available in that same session. (As I was saying, the Docker image seems to make a clean start each time, so it doesn't know about changes in a previous session.)
Controller parameters tuning without simulation
I'm pretty sure MATLAB requires you to pass either `float`s or `double`s, i.e. single/ double precision floating point numbers. At least all the examples I've seen use `double` arrays, the error message also points in that direction.
How can I display a vector and a matrix repeatedly when using fprintf
I need to store some really tiny positive and negative numbers in Matlab. One way is to store their signs separately, and the log10 of their magnitude, which lets me store numbers as small as 10^(-realmax)=10^(-10^308), effectively in double precision. But is there a way to use Matlab's sym and vpa to store numbers as small as this, with the magnitude and sign together, not separately, such that later I can extract their sign, and their order of magnitude, i.e. log10 of their absolute value, in double precision? I tried something like x=sym('-10^(-1e308)'), but this produces an error.
Is this what you are looking for? https://stackoverflow.com/questions/51158078/load-stl-file-in-matlab-and-convert-to-a-3d-array/51158671#51158671
You could use the diff (difference vs the previous sample) of the months array to look for when it changes, i.e. where the diff is non-zero. Then you find these indices and add two to them to offset by 2 weeks. idx = find([true; diff(m)~=0])+2; If you want to generate the 2nd column in your example then the full code would look something like % Example input data m = [202211, 202211, 202211, 202211, 202211, 202212, 202212, 202212, 202212]; % Find indices where month changes, offset by two weeks. % First sample is always true as we want to count the first week in the input % and "diff" returns an array one element shorter than the input dm = find([true; diff(m(:))~=0])+2; % Create an output with type "1" as the default and "2" for the 3rd-week indices dm( dm > numel(m) ) = []; % Handle edge case where the offset exceeded the array size aggType = ones(size(m)); aggType(dm) = 2; Prompted by @beaker's comment, here's a way to do it with a simple loop which keeps track of how many consecutive equal values there are for each sample, and then finds the corresponding indices by checking if the count equals 3. This is more robust to inputs which might not have 3 consecutive values the same in each batch. % Trickier input with <3 samples for some values, inc. at start m = [202210, 202210, 202211, 202211, 202211, 202211, 202211, 202212, 202212, 202212, 202212, 202301, 202301, 202302, 202302, 202302]; N = ones(size(m)); for ii = 2:numel(N) if m(ii) == m(ii-1) N(ii) = N(ii-1) + 1; % another consecutive equal value else N(ii) = 1; % reset the counter, value changed end end aggType = ones(size(m)); aggType( N==3 ) = 2; % N==3 are the desired samples
I used something similar with python pyATS framework, when complex E2E scenario was incorporated in one class with test methods as steps of its scenario with own checks. Although it isn't a unit test framework, so allow much more flexibility in different test structure approach.
So today I finally understood what is the purpose of the fftshift function found in both Matlab and Numpy &amp; Scipy implementations. Summary of my understanding: The natural order of fft's return values, does not match a linear space of frequencies from -dt to dt. Hence, to get a frequency array that matches an array of frequency terms (from the output of fft), you either need to fftshift a linspace from -1/dt to +1/dt, or you'd need to fftshift the output of fft. I am wondering though: Why isn't the fft function implemented in Matlab, Numpy and Scipy don't simply shift the output of it such that we'd get values that match linearly spaced frequencies from -1/dt to +1/dt? I'm sure there is a CPU/memory performance consideration here, but it'd be nice to get a thorough explanation for that. Even if the CPU/memory performance consideration will be justified, it'd be nice to hear about examples of calculations that won't require you to fftshift a linearly spaced frequencies from -1/dt to +1/dt (or use Numpy's fftfreq), and therefor that would be more performant thanks to the fft returning an array in it's current, natural order. One example I could think about for the above performance gain is convolution, which can be implemented as element-wise multiplication of fft outputs, (which therefor don't care about the order of the values, as long as it is consistent of course). Perhaps there are other reasons not to fftshift by default the output of fft, which are worth mentioning.
In MATLAb you can give `dbstop if warning` to have execution pause in the debugger at the point that a warning is issued. In the debugger you have access to the full call stack, as well as all the variables that exist at each level of the call stack.
I'm using Matlab notation. I have a matrix A of size (Nx3) where each entry of A is a positive integer. I want to create a matrix Q of dimensions (max(max(A))x2). Row i of Q corresponds to the column indices of A so that A(k,r) = i. So, if A(k_1,r_1) = i and A(k_2,r_2) = i, we can set Q(i,:)=[k_1,k_2]. For the unique entries of A, the associated row of Q has each column equal. Is there a way to vectorize the task? I can perform the task using loops, but it is very inefficient in MATLAB (when matrix A has large rows and max(max(A)) is also big). Here is an example. A=[ 1 10 9 1 2 4 3 2 11 3 12 5 6 13 4 6 7 15 8 7 5 8 14 16] In the above example, the expected result would be Q = 1 1 2 2 1 1 3 3 3 3 1 1 2 2 1 1 3 3 2 2 3 3 2 2 2 2 2 2 3 3 3 3 This is what my slow code does max_Q = max(max(A)); Q = zeros(max_Q,2); for i = 1 : max_Q [~,cols] = find(i == A); Q(i,:) = cols; end
Is there a programmatic way to generate s-functions directly out of Simulink blocks
The workflow can be summarized as follows: Code generation settings: Change the system target file to 'rtwsfcn.tlc'. In Code generation settings enable 'create new model' In Code generation settings uncheck 'Generate code only'. Once the above steps are done go ahead with building the model block programmatically: oldBlockPath=getfullname(gcbh); newBlockHandle=slbuild(gcbh) % gcbh points to handle of current selected block newBlockPath=getfullname(newBlockHandle); pil_block_replace(oldBlockPath,newBlockPath); The above code snippet can implement the idea at a fundamental level for a selected block. Reference: MATLAB Answer's
Please supply a reproducible example. These functions are called from a script. That script would be helpful.
Please extract the part that that does the optimization, the part that you replace with a MATLAB function and found to be wrong. And then only post that part, with a small driver script that sets the input values. The rest is irrelevant to your question, and just makes it harder for us to help you. See [mre].
I am trying to run a psychophysics experiment in MATLAB, where timings of stimuli are very crucial. I have code to generate a sequence of ones, twos, and threes, each of which will trigger different stimuli to be displayed. When stimulus 2 is displayed, the participant has 1s to respond via a button press (using a ResponsePixx button box). I need each stimulus to be delivered 0.5s after the previous, which means that the response time to stimulus 2 overlaps with the delivery of the following stimulus. So I think I need to somehow track for the button press in the background whilst continuing to deliver the stimuli sequence. Here's the simplified version that just reduces it down to this current problem: % Create sequence of numbers sequence = %FUNCTION OUTPUTS 1XN SEQUENCE OF ONES, TWOS, AND THREES for iSequence = 1:length(sequence) disp(sequence(iSequence)) % Stand-in for displaying proper stimuli if sequence(iSequence) == 2 % wait for 1 second whilst continuing display of sequence) % During this time, other code will run to track for participant responses disp("Time elapsed") end pause (0.5) end I have done some testing with parfeval with no success - the output is displayed correctly, but interrupts the timing of the main sequence delivery (I assume as a delay to fetching the outputs from the parallel pool, but to be honest I have very little experience with parallel processing so I'm not sure): delete(gcp('nocreate')) clear background = parpool(1); sequence = % createTrialSequence for iSequence = 1:length(sequence) disp(sequence(iSequence)) if iSequence > 1 if sequence(iSequence - 1) == 2 fetchOutputs(evalButton) end end if sequence(iSequence) == 2 evalButton = parfeval(background, @trackInBackground, 1); end pause(0.5) end I have also tried using an event and listener, but this also pauses the delivery of the sequence (again, not hugely familiar with how these work, so may be missing something crucial): clear event = targetAppeared; listener = trackTargetAppearance(event); sequence = %createTrialSequence for iSequence = 1:length(sequence) disp(sequence(iSequence)) if sequence(iSequence) == 2 event.isTarget end pause(0.5) end classdef targetAppeared < handle events targetEvent end methods function isTarget(obj) notify(obj, 'targetEvent') end end end classdef trackTargetAppearance < handle methods function obj = trackTargetAppearance(targetObj) addlistener(targetObj, 'targetEvent', @trackTargetAppearance.handleEvent) end end methods (Static) function handleEvent(~, ~) startTime = GetSecs; %get system time, from PsychToolBox while GetSecs < (startTime + 1) continue end disp("Target Response Window elapsed") end end end
I am working on a Bluetooth LE mesh network project with various devices distributed in an urban environment. My goal is to determine the minimum node density per square kilometer required for the network to function effectively. To explore this, I am using MATLAB, specifically the Bluetooth Toolbox library, to simulate a Bluetooth mesh network within a 200x200 meter area. In the simulation: N nodes are randomly generated alongside a few buildings (represented as gray blocks). A transmitter and receiver are selected. The mesh network is initialized, and packets are exchanged over a 10-second period. The script identifies active links between nodes based on the remaining power, which is calculated as the difference between the transmission power and the path loss. If the remaining power exceeds -70 dBm (the detection threshold for most receivers), the link is considered active. These active links are displayed on a figure using color grading. However, i am encountering two major issues: I am struggling to correctly implement attenuation for BLE propagation using Free-Space Path Loss. Even when active links are present, the simulation often returns zero values for key metrics like Latency, Packet Loss Ratio (PLR), and Packet Delivery Ratio (PDR), which is not the expected outcome. CODE: % Initialize the wireless network simulator networkSimulator = wirelessNetworkSimulator.init; % Parameter to enable or disable the maximum distance constraint maintainDistanceConstraint = true; % Set to false to disable the maximum distance constraint % Define the area and node parameters areaSide = 200; numNodes = 12; % Total number of nodes minReceivedPower = -70; % Minimum received power threshold in dBm maxDistance = 70; % Maximum distance between nodes (valid only if maintainDistanceConstraint is true) maxLinkDistance = 100; % Maximum distance to consider a link active transmissionPower = 20; % Transmitted power in dBm % Operating frequency of the Bluetooth LE signal (2.4 GHz) frequency = 2.4e9; % Function to calculate free space path loss calculateFreeSpacePathLoss = @(distance, frequency) ... 20 * log10(distance) + 20 * log10(frequency) - 147.55; % Result in dB % Initialize the position matrix nodePositions = zeros(numNodes, 3); % Including z = 0 % Random generation of rectangular obstacles (buildings) without overlap numBuildings = 5; % Number of buildings buildings = struct('x', [], 'y', [], 'width', [], 'height', []); for i = 1:numBuildings validBuilding = false; maxAttempts = 1000; attempts = 0; while ~validBuilding && attempts < maxAttempts attempts = attempts + 1; % Random dimensions for the building (between 20x20 and 80x80 meters) width = 20 + rand * 60; height = 20 + rand * 60; % Random position for the building x = rand * (areaSide - width); y = rand * (areaSide - height); % Check for overlap with existing buildings overlap = false; for j = 1:i-1 if ~(x + width < buildings(j).x || buildings(j).x + buildings(j).width < x || ... y + height < buildings(j).y || buildings(j).y + buildings(j).height < y) overlap = true; break; end end if ~overlap validBuilding = true; buildings(i).x = x; buildings(i).y = y; buildings(i).width = width; buildings(i).height = height; end end if ~validBuilding warning("Could not place building %d without overlaps after %d attempts.", i, maxAttempts); end end % Node generation with or without maximum distance constraint for i = 1:numNodes validPosition = false; nodeAttempts = 0; maxNodeAttempts = 1000; while ~validPosition && nodeAttempts < maxNodeAttempts nodeAttempts = nodeAttempts + 1; newPosition = rand(1, 2) * areaSide; if maintainDistanceConstraint && i > 1 distances = sqrt(sum((nodePositions(1:i-1, 1:2) - newPosition).^2, 2)); distanceSatisfied = any(distances <= maxDistance); else distanceSatisfied = true; end insideBuilding = false; for j = 1:numBuildings building = buildings(j); if newPosition(1) > building.x && newPosition(1) < (building.x + building.width) && ... newPosition(2) > building.y && newPosition(2) < (building.y + building.height) insideBuilding = true; break; end end if distanceSatisfied && ~insideBuilding validPosition = true; nodePositions(i, 1:2) = newPosition; end end if ~validPosition warning("Could not position node %d respecting constraints after %d attempts.", i, maxNodeAttempts); end end % Randomly select the transmitter and receiver randomIndices = randperm(numNodes, 2); transmitterIndex = randomIndices(1); receiverIndex = randomIndices(2); % Create the transmitter node sourceNode = bluetoothLENode("broadcaster-observer", ... Name="Source Node", ... Position=nodePositions(transmitterIndex, :), ... TransmitterPower=transmissionPower); % Set transmission power % Create the receiver node destinationNode = bluetoothLENode("broadcaster-observer", ... Name="Destination Node", ... Position=nodePositions(receiverIndex, :), ... TransmitterPower=transmissionPower); % Set transmission power % Configure Mesh profile for the transmitter node cfgMeshSource = bluetoothMeshProfileConfig(ElementAddress="0001"); sourceNode.MeshConfig = cfgMeshSource; % Configure Mesh profile for the receiver node cfgMeshDestination = bluetoothMeshProfileConfig(ElementAddress="0002"); destinationNode.MeshConfig = cfgMeshDestination; % Create relay nodes relayNodes = cell(1, numNodes - 2); % Initialize the relay nodes array relayCounter = 1; for i = 1:numNodes if i ~= transmitterIndex && i ~= receiverIndex relayNode = bluetoothLENode("broadcaster-observer", ... Name=sprintf("Relay Node %d", relayCounter), ... Position=nodePositions(i, :), ... TransmitterPower=transmissionPower); % Set transmission power relayNodes{relayCounter} = relayNode; % Add relay node relayCounter = relayCounter + 1; end end % Create network traffic traffic = networkTrafficOnOff(OnTime=inf, DataRate=1, PacketSize=15, GeneratePacket=true); addTrafficSource(sourceNode, traffic, SourceAddress="0001", DestinationAddress="0002", TTL=10); % Create the `nodes` array nodes = [{sourceNode}, relayNodes, {destinationNode}]; addNodes(networkSimulator, [nodes{:}]); % Calculate active links and received power linkMatrix = zeros(numNodes); % Adjacency matrix linkPower = zeros(numNodes, numNodes); % Residual power for links minResidualPower = inf; % Minimum power value maxResidualPower = -inf; % Maximum power value fprintf("\nActive links in the mesh network:\n"); for i = 1:numNodes %{ - Check the distance between nodes. - Check for obstacles (buildings) on the link. - Calculate received power considering path loss. - Register the link as active if the received power exceeds the threshold. - Update the minimum and maximum residual power values. - Print active link information. %} for j = 1:numNodes if i ~= j distance = pdist2(nodePositions(i, :), nodePositions(j, :)); if distance <= maxLinkDistance % Check if a building is between the nodes buildingAttenuation = false; midX = (nodePositions(i, 1) + nodePositions(j, 1)) / 2; midY = (nodePositions(i, 2) + nodePositions(j, 2)) / 2; for k = 1:numBuildings building = buildings(k); if midX > building.x && midX < (building.x + building.width) && ... midY > building.y && midY < (building.y + building.height) buildingAttenuation = true; break; end end if ~buildingAttenuation % Calculate path loss pathLoss = calculateFreeSpacePathLoss(distance, frequency); receivedPower = transmissionPower - pathLoss; if receivedPower >= minReceivedPower linkMatrix(i, j) = 1; % Active link linkPower(i, j) = receivedPower; minResidualPower = min(minResidualPower, receivedPower); maxResidualPower = max(maxResidualPower, receivedPower); fprintf("Node %d -> Node %d: Distance = %.2f m, Received Power = %.2f dBm\n", ... i, j, distance, receivedPower); end end end end end end % Run the simulation simulationTime = 10; run(networkSimulator, simulationTime); % Retrieve and display statistics sourceStats = statistics(sourceNode); destinationStats = statistics(destinationNode); relayStats = cellfun(@statistics, relayNodes, 'UniformOutput', false); disp("Transmitter node statistics:"); disp(sourceStats); disp("Receiver node statistics:"); disp(destinationStats); % Calculate and display KPIs latency = kpi(sourceNode, destinationNode, "latency", Layer="App"); plr = kpi(sourceNode, destinationNode, "PLR", Layer="App"); pdr = kpi(sourceNode, destinationNode, "PDR", Layer="App"); fprintf("\nBluetooth Mesh Network KPIs:\n"); fprintf("Latency: %.2f ms\n", latency * 1000); % Converted to milliseconds fprintf("Packet Loss Ratio (PLR): %.2f\n", plr); fprintf("Packet Delivery Ratio (PDR): %.2f\n", pdr); % Visualize the mesh network figure; hold on; % Draw buildings for i = 1:numBuildings rectangle('Position', [buildings(i).x, buildings(i).y, buildings(i).width, buildings(i).height], ... 'FaceColor', [0.5 0.5 0.5], 'EdgeColor', 'k'); end % Draw nodes for i = 1:numNodes if i == transmitterIndex scatter(nodePositions(i, 1), nodePositions(i, 2), 250, 'r', 'filled'); % Transmitter (red) elseif i == receiverIndex scatter(nodePositions(i, 1), nodePositions(i, 2), 250, 'g', 'filled'); % Receiver (green) else scatter(nodePositions(i, 1), nodePositions(i, 2), 200, 'b', 'filled'); % Other nodes (blue) end end % Draw links for i = 1:numNodes for j = 1:numNodes if linkMatrix(i, j) == 1 powerNorm = (linkPower(i, j) - minResidualPower) / ... (maxResidualPower - minResidualPower); linkColor = [1 - powerNorm, powerNorm, 0]; % Gradient from red to green plot([nodePositions(i, 1), nodePositions(j, 1)], ... [nodePositions(i, 2), nodePositions(j, 2)], '-', ... 'Color', linkColor, 'LineWidth', 2); end end end title('Distribution of Nodes, Buildings, and Active Links in the Bluetooth Mesh Network'); xlabel('X Position (meters)'); ylabel('Y Position (meters)'); xlim([0 areaSide]); ylim([0 areaSide]); grid on; axis equal; hold off; enter image description here Currently, my approach is as follows: Set a transmission power of 20 dBm for each node. Use a free-space path loss function to calculate attenuation based on the distance between nodes. Determine active links if the remaining power exceeds -70 dBm and reflect these links in the linkMatrix and linkPower matrices. I am trying to adjust the simulation to only process data and compute metrics using the active links, but i am unsure how to implement this next step. I also know from the official MATLAB documentation that there is a way to account for attenuation directly using built-in library functions, but i am struggling to integrate this feature into the programming logic. What i expect is for the script to compute and return realistic, non-zero values for Latency, Packet Loss Ratio (PLR), and Packet Delivery Ratio (PDR) when the transmitter and receiver are actively linked.
That is exactly what I mean with "for visualization". If you're not looking at it, it doesn't matter whether it looks pretty or not.
I have two matrices: A = [ -1 0 0; 1 1 -1; 0 -1 1 ]; B = [-1; 0; 1]; and I want to solve the following equation: Ax=B when I use mldivide function I get a matrix of NaNs X = mldivide(A,B) X = NaN NaN NaN Knowing there are multiple solutions to this problem I manually tested if one of them, namely [1;0;1] returns B: A*[1; 0; 1] and, as expected, I reassured myself that it is one of multiple solutions. So here is my question: why does mldivide return incorret solution?
Why was `fftshift` invented for? Why not `fftshift` by default the output of the current `fft` implementations?
Thank you for the response, your solution #2 is more inline with what I'm trying to do, but when I use that solution, I get the error: Error in initialize/init (line 39) app.buttons = buttons( app.gridLayout ); ^^^^^^^^^^^^^^^^^^^^^^^^^ Error in initialize (line 52) init(app) ^^^^^^^^^
@CrisLuengo: I guess that answers one possible reading of the question, like "does MATLAB pin its threads to the P-cores to match its default thread count?" (i.e. is thread pinning part of the distinction it makes). And this is answering "no". That isn't what I thought it was asking, which as I commented under the question, I think it's asking how MATLAB figures out which cores are which so it can count the number of physical P cores in the first place. This answer doesn't answer that at all. OS thread APIs don't currently report E vs. P core counts; they predate such CPUs.
if so, then please either post a self-answer or delete the question altogether
Hi @jonsson this was helpful so thank you. What I found that worked well was instead of trying to write the commands in MATLAB and such having to convert the VBA into a compatible format for MATLAB, was rather to just write a VBA macro that created the TOC and made it hyperlinks and then call this macro in my MATLAB script. This way I can do the data processing I need to in MATLAB and then simply call the VBA commands that I couldn't convert, as macros. This solved my problem entirely.
The error message "error using norm first argument must be single or double" pretty clearly indicates that your array has to be `float` or `double` rather than `int`. Have you tried `double[,] input = new double[...] ...`?
You can get the common timestamps, then filter A and B for columns with timestamps in this array t = intersect( A(1,:), B(1,:) ); % Get common timestamps A = A( :, ismember(A(1,:), t) ); % Only retain cols with timestamps in common array B = B( :, ismember(B(1,:), t) ); % Only retain cols with timestamps in common array Alternatively, you could just remove columns from A where the timestamp isn't in B, and then vice versa: A( :, ~ismember(A(1,:),B(1,:)) ) = []; % Remove A cols not in B's timestamps B( :, ~ismember(B(1,:),A(1,:)) ) = []; % Remove B cols not in A's timestamps
I noticed an issue: if the size of the training set images differs significantly from the test set images, reducing the test images to match the training size may cause feature loss. Will this have a significant impact?
Agreed. If only Mathworks had given us run-length encoding and cumulative run-length.
Yea, all of the integers [1:max(max(A))] guaranteed to appear. That is correct, setting Q(i,:)=[k_1,k_1] when there is only one instance of i.
Why do I get a "Unable to find connector client." error when using restFunctionService
Restart simulation when slider gain value is adjusted
Thank you . Figured it to be the issue .
And will there ever be a case where `k_1 != k_2`? It doesn't appear so from your example.
Direct Sequence Spread Spectrum (DSSS) of Binary Phase Shift Keying (BPSK)
This is a potential solution using a timer Excuse the clutter of code due to building a minimal GUI for this, the only mechanisms to focus on are: Use a timer to trigger the stimuli display/change at regular interval (in particular, look at the ExecutionModeoption of the timer, which lets you adjust how regular the timer firing is) When the stimuli necessitating a (timed) response from the user is displayed, start a stopwatch When the user button press is detected, read the value of the stopwatch and act in consequence. The code for the example above: function hf = TimedResponse global sequence ; sequence = 1:10 ; hf = build_gui ; end function myTimerFcn(~,~,hfig) global sequence ; global responseTimer ; persistent iseq ; hf = guidata(hfig) ; if isempty(iseq) ; iseq=1 ; end if iseq&gt;numel(sequence) ; iseq=1 ; end hf.lbl.String = num2str(sequence(iseq)) ; if sequence(iseq) == 2 responseTimer = tic ; end iseq = iseq+1 ; end function StartButtonPushed(src,~) hf = guidata(src) ; if strcmpi(hf.t.Running,'off') start(hf.t) ; hf.btnStart.String = 'Stop'; else stop(hf.t) ; hf.btnStart.String = 'Start'; end end function RespButtonPushed(src,~) global responseTimer ; hf = guidata(src) ; ElapsedTime = toc(responseTimer) ; if ElapsedTime &lt; 1 hf.lblresp.ForegroundColor = 'g' ; hf.lblresp.String = sprintf('*** PASS *** (Time to respond to stimuli: %f seconds)',ElapsedTime) ; else hf.lblresp.ForegroundColor = 'r' ; hf.lblresp.String = sprintf('*** TOO LATE *** (Time to respond to stimuli: %f seconds)',ElapsedTime) ; end end function h = build_gui h.fig = figure('unit','normalized','CloseRequestFcn',@my_closereq); h.t = timer('Period',0.5,'ExecutionMode','fixedDelay') ; h.t.TimerFcn = @(e,v)myTimerFcn(e,v,h.fig) ; h.btnStart = uicontrol('Style','pushbutton','String','Start','unit','normalized','Position',[0.1 0.8 0.8 0.1],'Callback',@StartButtonPushed); h.lbl = uicontrol('Style','text','String','0','unit','normalized','Position',[0.1 0.4 0.8 0.3],'FontSize',36); h.btnResp = uicontrol('Style','pushbutton','String','Stimuli observed','unit','normalized','Position',[0.1 0.2 0.8 0.1],'Callback',@RespButtonPushed); h.lblresp = uicontrol('Style','text','String','','unit','normalized','Position',[0.1 0.1 0.8 0.05],'FontSize',12); h.seq = 1:10 ; guidata(h.fig,h) end function my_closereq(src,~) hf = guidata(src) ; disp('Deleting timer') ; if strcmpi(hf.t.Running,'on') stop(hf.t) ; end delete(hf.t) ; delete(hf.fig) ; end
I managed pass an identifier to the MATLAB Function blocks allowing me to trace the origin of prints or warnings afterwards, by following these steps : Create a mask parameter on top of the MATLAB Function. Pass the parameter as input to the MATLAB function in the function definition. This step requires specifying the entry as a Parameter Data within the Modeling/Symbols Pane panel. Run a script that set up the identifier for each of the MATLAB Function blocks. When the model runs, and displays warnings it prints the identifier as well as the warning for debugging purposes. Note : I did not manage to pass the path to the block (model_name/subsystem/subsytem2/etc...) as a string as intended, but instead relied on the fact that I have a numerical identifier for each block of the model, which is specific to my application. I believe this can be improved, maybe with a more generic answer, but this has solved my issue in my application for now.
Are you asking how it classifies a core as P or E after checking its `cpuid` results or something? On current systems, the max MHz for E cores is lower than P cores, so that's one common way to check. The model/family info may be the set to report the same because some anti-piracy software assumed real systems were homogeneous, so it's not as easy as just looking at model/family. Related: [How to detect P/E-Core in Intel Alder Lake CPU?](https://stackoverflow.com/q/69955410) / [How to detect E-cores and P-cores in Linux alder lake system?](https://stackoverflow.com/q/71122837)
I have a question to the command fft in Matlab. By using the default settings Matlab assumes the signal to be periodic with a periodicity of 2π. However, for my problem I need to apply the FFT to a signal that is periodic in L ≠ 2π. I am sure there is a proper function for this in Matlab. I am pretty new in Matlab and I didn't find anything in the documentation of fft. To be precise: I want fast fourier transform an array with N emenets by using the frequencies [0, L/N,..., L*(N-1)/N]. I know that it would be easy to write a code by simply calculating the fft manually, but I guess there must be an efficient command available in matlab.
In Matlab, I am doing a curve fitting of a set of points, which follow a power law. If I use the 'log(a*x^n)' power law as the main argument of the fittype function, everything works well: % input x = [4 9 15 25 35 45 55 65 75 85 95 150 250 350 450 900]; y = [335 28 37 9 4 3.5 2 1 0.7 0.6 0.5 0.3 0.1 0.01 0.005 0.001]; % curve fitting ft = fittype('log(a*x^n)','independent','x'); [fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1]); % plots hold on plot(x,y,'o-','Color','b') plot(x,(fitresult.a .* (x.^fitresult.n)),'-','color','r') set(gca, 'XScale', 'log', 'YScale', 'log'); However, if I add an additional parameter, b (i.e. the y-intercept), to the previous power law, i.e. now being 'log(a*x^n + b)', in the fittype function... % input x = [4 9 15 25 35 45 55 65 75 85 95 150 250 350 450 900]; y = [335 28 37 9 4 3.5 2 1 0.7 0.6 0.5 0.3 0.1 0.01 0.005 0.001]; % curve fitting ft = fittype('log(a*x^n + b)','independent','x'); [fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1 1]); % plots hold on plot(x,y,'o-') plot(x,(fitresult.a .* (x.^fitresult.n)),'-') set(gca, 'XScale', 'log', 'YScale', 'log'); I get the following error: Error using fit&gt;iFit Complex value computed by model function, fitting cannot continue. Try using or tightening upper and lower bounds on coefficients. Error in fit (line 117) [fitobj, goodness, output, convmsg] = iFit( xdatain, ydatain, fittypeobj, ... Error in untitled6 (line 6) [fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1 1]); How can I solve this error and - in general - make the fittype function work for a logged power law which includes a y-intercept?
The issue I thought I had with generating a uuid from my octave script was a red herring. Within the the function I was calling, I'm doing extract(epoch from tts.timestampt); it was the numeric value returned by postgres that was actually giving octave trouble. Changing that data type allowed my function to execute as expected with a uuid parameter.
Alternatively, change the assignment in your loop to `fourdmatrix(:,:,:,i) = cell{i};`
I discovered that it has to do with both numerical precision and permutation. In Julia, I computed: `R = sparse(cholesky(K).L)'` without permuting it to better condition the matrix, and to my surprise, I got exactly the same result as in MATLAB, with a difference in the 18th decimal place.
To add on Ander's coment, the MATLAB fft2 is already using multithreading and is quite fast.
If graph coloring is, in fact, what you're looking for, 4-coloring a planar graph isn't hard, so it would definitely be feasible to write your own. We just need clarification on your expected output.
Sorry about that, heres the full error, >> initialize Error using uibutton (line 55) 'Parent' must be a parent component, such as a uifigure object. Error in buttons (line 9) obj.fileload1 = uibutton(grid, 'push'); ^^^^^^^^^^^^^^^^^^^^^^ Error in initialize/init (line 39) app.buttons = buttons( app.gridLayout ); ^^^^^^^^^^^^^^^^^^^^^^^^^ Error in initialize (line 52) init(app) ^^^^^^^^^
Regarding SOS, no it is not just the same array, the function `butter` has a input parameter called `output` which can be set to `sos`.
Your vector n is not smooth, and doesn't represent a parallel gradient to any vector direction. You can see this by just using plot(n), it aligns with the representation you get. This code shows how you can plot a gradient perpendicular to a given vector: You can use atan2 to work out the direction of your vector aUV, and set the colour equal to cos(theta + aUV + pi/2), since you want to start drawing the colours offset by aUV from where you're drawing the circular patch and the additional pi/2 makes the gradient perpendicular. % Some setup values N = 32; % Number of samples in array U = -4.6492; % X displacement of vector V = -0.9099; % Y displacement of vector % Calculate circle drawing vectors aUV = atan2(U,V); % Angle of UV vector theta = linspace(0,2*pi,N); % Angle array for drawing patch clr = cos(theta + aUV + pi/2); % Offset cyclic colour starting from aUV+pi/2 % Plot figure(1); clf; hold on; patch(cos(theta), sin(theta), clr, 'EdgeColor', 'none'); quiver(0,0,U,V,0.5,'k','linewidth',3); axis equal; colormap spring Output: Edit with respect to question update... If you do not have the angle or direction vector as an input we can determine it from the input n by Upsampling with piecewise cubic interpolation Finding the peak Plotting in a similar way to above See the code comments for details % Sort theta so that we can interpolate with it as the axis [theta,idx] = sort(theta); n = n(idx); % Match the order of points in 'n' with sorted theta % Upsample 'n' using piecewise cubic interpolation theta_i = linspace(theta(1),theta(end),1000); n_i = interp1( theta, n, theta_i, 'pchip' ); % Find the index for the max value of 'n' [n_max,idx] = max(n_i); aUV = theta_i(idx); % Offset cyclic colour starting from aUV clr = cos(theta - aUV); % Plotting... side by side of input curve with gradient for comparison label = sprintf('\\theta=%.3f',aUV); % helper for legend labelling figure(1); clf; subplot(1,3,1); hold on; plot(theta,n,'displayname','Input "n"'); plot(theta_i,n_i,'displayname','Upsampled "n"'); plot(aUV,n_max,'kx','displayname',['Peak "n" at ' label]); legend('show','location','south'); subplot(1,3,2:3); hold on; patch(cos(theta), sin(theta), clr, 'EdgeColor', 'none','displayname','gradient'); line( [-1,1]*cos(aUV), [-1,1]*sin(aUV), 'color', 'k', 'displayname', ['Ref line at ' label]); axis equal; colormap parula; legend show Result:
The MSDN VBA documentation is usually a good reference for how to programmatically control Excel from MATLAB, since the syntax with the COM interface for Excel is closely aligned with VBA. In particular, from the GoalSeek VBA docs: https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa195749(v=office.11) The VBA code would be something like: Worksheets("Sheet1").Range("C3").GoalSeek _ Goal:=15, _ ChangingCell:=Worksheets("Sheet1").Range("B3") We can do this in MATLAB as follows: workbookName = 'Test.xlsx'; sheetName = 'Sheet1'; goalseekAddr = 'C3'; goalseekVal = 15; changeAddr = 'B3'; sheet = getSheet( workbookName, sheetName ); changeCell = sheet.Range(changeAddr); invoke( sheet.Range(goalseekAddr), 'GoalSeek', goalseekVal, changeCell ); You have to use invoke to call the GoalSeek function, but otherwise it's operating on the same inputs It's a function of the range you wish to seek on The first input argument is the value to seek for The second input is the cell to change getSheet is a helper function I've written, but you might already have something which gets the sheet COM object via actxserver Helper function function sheet = getSheet( workbookName, sheetName ) % Try and connect to open Excel instance, open a new one if not try Excel = actxGetRunningServer('Excel.Application'); catch Excel = actxserver('Excel.Application'); end % Find the workbook by name workbook = []; for iwb = 1:Excel.Workbooks.Count if strcmpi( workbookName, Excel.Workbooks.Item(iwb).Name ) workbook = Excel.Workbooks.Item(iwb); break; end end if isempty(workbook) Excel.Workbooks.Open( workbookName ); end % Assume the sheet exists... sheet = workbook.Sheets.Item(sheetName); end
One you have the data in a 4d array it's simple enough, just use mean and supply the dimension to work over as you suggest. As @Cris notes you might run out of memory forming the 4d array (since it will copy all the data) in which case you'll want to loop over the existing arrays. But if you have enough memory this should work: % make 12 random 3d arrays in cell array `c` for i=1:12 c{i} = rand(10, 10, 10); end % Make a 4d array: array4d = cat(4, c{:}); % Same as writing cat(4, c{1}, c{2}, c{3}, etc) m = mean(array4d, 4); % Take the mean along the 4th dimension size(m) % Show the size of the output (here should be 10,10,10)
Why have you set MaxIter to 2000? do you really know if below 2000 it has all converged?
Represent tiny numbers in Matlab using sym and vpa
I have a MATLAB code that is copying data to an Excel file and running hundreds of formulas (for anyone interested, I am using a revised version of CREST developed by NREL). Afterwards, I want to run a What-If Analysis using the goal seek ability in Excel to find the minimum cost of the product. Because of the complexity of the spreadsheet, I cannot recreate the formulas in MATLAB (in a timely fashion). The What-If Analysis works manually, but I would like to run goal seek for thousands of files. Is there a way to use MATLAB to execute this? I would like to open the spreadsheet, run the goal seek, save, and close the file and do this for thousands of files. I know how to do everything other than execute the goal seek. Thank you!
I am trying to create an FIR and associated waveform for a transfer function that is the magnitude difference between the two impulses responses. I have recorded both IR's but am struggling with getting the correction factor to be correct. Here is my code and results of the IRs and difference which is clearly wrong because it is reducing magnitude incorrectly. I can see kind of where it is going wrong which seems to be in taking the difference between them which results in the following magnitude graph and DBFS graph. I have included wav files as csv if trying to run. EDIT: updated code to show my target curve and the resulting correction curve. I have changed the code to divide instead of subtract as suggested which got me the result I desired. HOWEVER now when I look at the time-domain FIR of the correction curve it looks really wrong and funky. time-domain plot of y result here is the new code that should work. % Define the sampling frequency close all [x1,fs] = audioread('711_Tap1024.wav'); [x2,fs] = audioread('5128_Tap1024.wav'); Nfft = length(x1); % Frequency vector (assume frequencies are normalized, or you need to normalize by fs/2) f = linspace(0, fs, Nfft); f = f'; %define Target Curve x1FR = 20*log10(abs(fft(x1,Nfft))); x2FR = 20*log10(abs(fft(x2,Nfft))); targetCurve = x1FR-x2FR; targetCurve = targetCurve*-1; % Define or import the frequency responses H1 and H2 % H1 = abs(fft(x1,Nfft)); % H2 = abs(fft(x2,Nfft)); H1 = fft(x1,Nfft); H2 = fft(x2,Nfft); % Compute the difference in frequency responses divide %H_diff = H1-H2; H_diff = H2./H1; % Inverse FFT to obtain the impulse response y = real(ifft(H_diff,Nfft)); % Normalize the impulse response y = 0.99*y/max(abs(y)); % Save the impulse response as a WAV file audiowrite('impulse_response_diff.wav', y, fs); % Plot the impulse response (optional) figure; plot(y) % plot result of y y_new=abs(fft(y,Nfft)); y_new= 20*log10(y_new); figure plot(f(1:Nfft/2), x1FR(1:Nfft/2)); hold on plot(f(1:Nfft/2), x2FR(1:Nfft/2)); hold on plot(f(1:Nfft/2), targetCurve(1:Nfft/2)); hold on plot(f(1:Nfft/2), y_new(1:Nfft/2)); xlim([20 20000]) xticks([100 1000 10000]) grid on set(gca, 'XScale', 'log') xlabel ('Frequency (Hz)'); ylabel ('Magnitude'); legend('H1', 'H2', 'Target Curve','Correction Curve')
There is a four-dimensional matrix data, along with corresponding X coordinates data_X and Y coordinates data_Y for each element. I want to perform a two-dimensional interval segmentation, or grid partitioning, based on edge_X and edge_Y, resulting in a new array data_class. The current loop implementation is very slow. How can I improve the computational speed? clc;clear rng("default") data = randi([0, 100], 40,30,20, 10); data_X = randi([0, 100], 40,30,20, 10); data_Y = randi([0, 100], 40,30,20, 10); % Define the edges for histograms in X and Y directions edge_X = [0:10:100]; edge_Y = [0:20:100]; sz = size(data); for ix = 1:sz(1) for iy = 1:sz(2) for ii = 1:sz(3) for ij = 1:sz(4) % Extract the current data, X, and Y values g_data = data(ix, iy, ii, ij); g_X = data_X(ix, iy, ii, ij); g_Y = data_Y(ix, iy, ii, ij); % Compute the 2D histogram count g_id = histcounts2(g_X, g_Y, edge_X, edge_Y); g_new = g_id * g_data; data_class (ix,iy,ii,ij,:,:) = g_new; end end end end Since each element of data is processed individually, g_data will only be noted as 1 in a bin, and then g_new = g_id * g_data; g_new is the position of g_data after reclassification The current loop implementation is very slow. How can I improve the computational speed?
What are “header file declarations”? Are you talking about include statements? Those are expected in a C file. Please clarify what you are seeing by including a [mre], and please explain why it is a problem. Also, don’t forget to ask a question explicitly. It makes it easier to provide an answer without guessing at what you want to learn.
The behavior you're observing is actually expected - runpf performs a power flow calculation to determine if a solution exists that satisfies Kirchhoff's laws and the specified power injections/demands, but it does not enforce branch flow limits by default. This is because branch flow limits are typically considered as operational constraints rather than physical laws. If you need to find a solution that respects branch flow limits, I would recommend you to use MATPOWER's OPF functionality instead. The OPF will try to find a solution that satisfies power flow equations, respect branch flow limits, keep voltages within bounds, respect generator limits and minimize generation cost. You can read more about it here: https://matpower.org/docs/ref/matpower5.0/opf.html
Just looking around *Windows* Word (without MatLab), when a TOC is generated by a field code, you generally need \ \h (backslash-h) in that code to make each entry in the TOC hyperlink. ActiveDocument.TablesOfCOntents(1).UseHyperlinks(1) = True does not appear to introduce a backslash-h, whereas if you do ActiveDocument.TablesOfContents.Add(rang,,,,,,,,,True) when you create the TOC, Word *does* insert the backslash-h. If I save that as .PDF I get hyperlinks to the headings...
@CrisLuengo a good example where I'm sure you'd agree with me it is natural to view the frequency range from -N/2 to N/2 is the classical Gaussian Fourier transform that should produce a Gaussian as well - take a Gaussian with mean at 0, corresponding to values from `-x0` to `x0`; Run `fft` on it; Isn't it natural to expect a shifted sample of a Gaussian from `-1/dx` to `1/dx`?
Possible duplicates https://stackoverflow.com/a/18277039/3978545, https://stackoverflow.com/questions/58957369/unable-to-convert-matlab-timestamp-to-datetime-in-python,
FFT to compute a Bode diagram to find resonance in MATLAB
[Here](https://stackoverflow.com/questions/25487090/matlab-matrix-neighbour-extraction) is a simple way to convert a labeled image into a graph with the labels as nodes and edges between adjacent labels.
How interesting. I've never done multithreading before, so I'll have to look into this. Thanks a bunch.
It's not even the advantage reasons behind it, i can’t run them separately because they are dependent: 2/ uses in its request the ID value which is produced by test 1/ successful run. This value is generated in response, so i can't set it for test 2/ by myself. So, either i need to share this produced value across the tests, or store somewhere in such a way to be able to get it from there for the next tests.
For each of 20 trials, I have a structure S, with 50 subfields. One of these subfields, type, is a 1x50000 structure with 50 fields. I need to add a field condition to the subfield structure 'type', to have S.type.condition. [S.type.condition] = deal(''); %adds the subfield to S.type This new subfields needs to be populated based on two of the existing subfields: S.type.pres (with values from 1 to 2) and S.type.stimulus (with values from 1 to 3), such that if `S.type.stimulus == 1 &amp; S.type.pres == 1` then `S.type.condition ==1` `S.type.stimulus == 2 &amp; S.type.pres == 1` then `S.type.condition ==2` `S.type.stimulus == 3 &amp; S.type.pres == 1` then `S.type.condition ==3` `S.type.stimulus == 1 &amp; S.type.pres == 2` then `S.type.condition ==4` `S.type.stimulus == 2 &amp; S.type.pres == 2` then `S.type.condition ==5` `S.type.stimulus == 3 &amp; S.type.pres == 2` then `S.type.condition ==6` I need to repeat this for each of the 20 trials.
There are obviously two steps here: extracting the color scale from the image, and writing it out to your chosen file format. Thus, there are two questions, not one. Please ask only one question per post. The first task has already been asked many times, a Google search should point you to those previous questions.
Edited it . Hope the question is more clear now.
I have also posted this question in MATLAB's forum https://www.mathworks.com/matlabcentral/answers/2162625-compiler-runtime-custominstaller-fails-to-reduce-mcr-installer-size from the reply by Sumukh, it appears that compiler.runtime.customInstaller is basically doing the same as deploytool, that creates a "reduce-sized" mcr package using only the components returned by requiredMCRProducts.txt. It is simply an API version of this function - one should not expect further mcr file size reduction by calling this API. Because of this, the mcr local installer is the best matlab can produce, it is rather a coarse-grained reduction based on the components, but it currently does not support fine-grained file-level trimming.
I use the commands: dbstop if error and dbstop if warning Is it possible to combine those conditions, to stop at either warning or error? As far as I tried, the latter doesn't catch both. Ideally, it would look something like: dbstop if (error || warning)
How to add a proxy CA certificate to MATLAB
I want to test wether there is a correlation between the (average) exam and deliverable marks obtained by each student, so I tried to do it using resampling testing. %% % Hypotheses: % H0​: There is no correlation between exam and deliverable marks (ρ=0). % H1​: There is a significant correlation between exam and deliverable marks (ρ≠0). %% % Calculate the observed correlation between exam and deliverable marks observed_corr = corr(marks_exams_perStudent, marks_deliverables_perStudent); % Bootstrap resampling for correlation coefficients nResamples = 10000; % Number of bootstrap resamples bootstrap_corrs = zeros(nResamples, 1); for i = 1:nResamples % Resample with replacement resample_indices = randi(size(marks_exams_perStudent, 1), size(marks_exams_perStudent, 1), 1); resample_exam = marks_exams_perStudent(resample_indices); resample_deliverable = marks_deliverables_perStudent(resample_indices); % Compute correlation for the resampled data bootstrap_corrs(i) = corr(resample_exam, resample_deliverable); end % Calculate the 95% Confidence Interval for the bootstrap correlations sorted_bootstrap_corrs = sort(bootstrap_corrs); lower_bound = sorted_bootstrap_corrs(floor(0.025 * length(sorted_bootstrap_corrs)) + 1); upper_bound = sorted_bootstrap_corrs(floor(0.975 * length(sorted_bootstrap_corrs))); % Display the confidence interval disp(['The 95% Confidence Interval for the correlation coefficient is: [' num2str(lower_bound) ', ' num2str(upper_bound) ']']); % Calculate the p-value for the observed correlation bootstrap_abs_corrs = abs(bootstrap_corrs); % Take absolute values of bootstrap correlations observed_abs_corr = abs(observed_corr); % Absolute value of observed correlation % Calculate the p-value (two-tailed) p_value = mean(bootstrap_abs_corrs &gt;= observed_abs_corr); disp(['p-value for the hypothesis test: ', num2str(p_value)]); I get the following results: The 95% Confidence Interval for the correlation coefficient is: [0.090306, 0.50174] p-value for the hypothesis test: 0.5187 So going by CI Im able to reject the hypothesis while by p-value Im not. What am I doing wrong?
I tried it out, it seems the 0 coefficients as you said are the actual numerators, such that the numbered values are b0, b2, b4, b6 and b8, while b1, b3, b5 and b7 are 0. the filter response for 4th order is very wierd, and it supposedly attenuates to -360 db, but the graphic response says otherwise, I think I'll stick to 1st or second order, thank you again. Maybe I'm misunderstanding again, but that's what testing's for.
You might want to ask about your specific use case over at [dsp.se], since you have a question about how to interpret the output of the FFT. It is not a question about programming (what this site is about).
I expect the smallest eigenvalue to be zero. And the following should be equdistant (this is at least true in the output).
Thank you ! Using coder.extrinsic breaks the possibility to use the code generation
I am modeling a simulation of an APM (Automated Power Management) system where the machine adjusts its gear and RPM to react to a variable workload. I am modeling it off a tractor. So, for this model the variable workload would be increasing/decreasing resistance force the tractor has to pull. I am stuck with the gearbox. I have the code determining wheel torque required, and I need to do an inverse table lookup. The table is set up like f(x,y)=z where x=Throttle Position/RPM, y=Gear and z=Wheel Torque. In this instance I know my throttle position, and I know torque required, I need a way for it to give me the corresponding gear. Here's what the table looks like: I know how to use the 2-D table look up to find z from x and y, but not to find y with x and z.
How can I improve my MATLAB code to isolate a QR code from images with various elements in their backgrounds?
Yes, you would have to generate the graph by finding the labels that are adjacent. Tedious, but not difficult given a labeled image.
I'm currently working on a project that involves isolating QR codes from images that contain various background elements. But I'm struggling to figure out how to isolate the QR code from the background. The images below show my attempt so far, but I've only managed to isolate the 3 corner squares and some white parts of the QR code. Although some of the isolated regions have unwanted artifacts. I'm very new to image processing so I'm learning how to use these image processing function while working on this project, so please excuse any simple mistake I've made. The challenges: The isolated region includes unwanted artifacts. I'm unsure if my structuring element is appropriate for the morphological operations for extracting QR codes. I've experimented with different threshold values, but the results vary significantly. Request for Feedback: Could someone provide insights on how to improve my morphological processing? Are there any specific techniques or adjustments you would recommend to better isolate the QR code patterns from the background image? My MATLAB code: % Read the input image img = imread('QR01.jpg'); % Convert to grayscale if the image is RGB if size(img, 3) == 3 img = rgb2gray(img); end % Set a threshold to create a binary image thresholdVal = 0.5; % Adjust as necessary threshold_img = imbinarize(img, thresholdVal); % Morphological operations to emphasize squares se = strel('square', 5); % Use a smaller structuring element to preserve finer details cleaned_img = imopen(threshold_img, se); % Remove small noise % Identify connected components in the cleaned image bConnectedComponents = bwconncomp(cleaned_img, 4); stats = regionprops(bConnectedComponents, 'Area', 'BoundingBox', 'Eccentricity', 'Extent'); % Initialize a blank image for the QR code qrCodeRegion = false(size(cleaned_img)); % Loop through each component to find potential QR patterns for k = 1:bConnectedComponents.NumObjects area = stats(k).Area; bbox = stats(k).BoundingBox; aspectRatio = bbox(3) / bbox(4); % Width / Height ratio extent = stats(k).Extent; % Ratio of area to bounding box area % QR finder patterns are approximately square with high extent (~1 for solid shapes) if area &gt; 100 &amp;&amp; area &lt; 1000 &amp;&amp; aspectRatio &gt; 0.8 &amp;&amp; aspectRatio &lt; 1.2 &amp;&amp; extent &gt; 0.6 % Mark this component as part of the QR code qrCodeRegion(bConnectedComponents.PixelIdxList{k}) = true; end end % Further dilation if needed to connect the finder patterns %qrCodeRegion = imdilate(qrCodeRegion, strel('square', 10)); % Show the isolated QR code region figure; imshow(img); title('Original QR Code image'); figure; imshow(qrCodeRegion); title('Isolated QR Code Region');
From [the docs](https://www.mathworks.com/help/matlab/matlab_prog/class-based-unit-tests.html#mw_c7446675-bdbf-4178-9e33-ead315793a26): “Unit tests in a matlab.unittest.TestCase subclass must run independently, without unintentionally affecting one another. In addition, they must be repeatable, which means that a running test must not affect subsequent reruns of the same test.”
@PeterCordes I don't think MATLAB would disclose that information so I fill the gap with some guesswork. I understand you have been following this topic for a while, so feel free to edit the answer.
this might be better asked on the [dsp.se] SE -- this question came from the [staging ground](https://stackoverflow.com/staging-ground/79216322)
Find column indices of a matrix entries that are repeated values
I want to compute FFT and IFFT on a large image via GPU. But my GPU is low on memory
Assigning to your local variable report_id makes the UUID literal type text effectively. Your second attempt is missing a FROM: query = "SELECT * FROM public.fn_func($1::uuid)"; But you should really get this error: ERROR: syntax error at or near "public" If that does not fix it, then I am not sure how your client manages to thwart the query. You could create an (overloaded?) function taking text and cast in the function (like Adrian commented), or you could concatenate the query string with an untyped literal: query = "SELECT * FROM public.fn_func('5ed30f08-0de0-47f4-99e8-9aeeb8eb2dfe')"; fiddle
@beaker I would not need an alpha for my use scenario
TeX formatting doesn't work here to render maths
You intend for `result` to be a single value, sum of all `outcome`? Because `outcome:outcome(100)` is an array with all integer values in between `outcome(1)` and `outcome(100)`, if both of them are integers, the other values in `outcome` would be ignored. I think you meant to do `outcome(1:100)`. What is `plot result` meant to do? `outcome(i)=randsample(sample,1);` would work if `sample` is defined as a numeric array as @wolfie suggested.
@Irreducible is correct. You have created filter coefficients that expose a numerical stability issue in the case of a 4th order Butterworth filter. See here for an explanation: https://en.wikipedia.org/wiki/Digital_filter#Direct_form_II Basically, DFII is a highly optimized implementation of a time domain convolution, but since the poles are calculated first, the gain can go extremely high, extremely fast and lead to numerical instability, especially in the case of high Q filters (which yours is an example of). Also, not sure why you see only 5 values for your bs, but scipy.signal.butter always returns the same number of coefficients for b and a. As suggested, express the filter as second order sections and your filter will be fine: import numpy as np import scipy as sp import matplotlib.pyplot as plt from scipy import signal fs=20000 bt,at= signal.butter(4,[7.692307692307693,13],'bandpass',fs=fs) b1,a1= signal.butter(1,[7.692307692307693,13],'bandpass',fs=fs) t = np.linspace(0, 1, fs, endpoint=False) freq = 10 sqr_wave = signal.square(2 * np.pi * 10 * t) plt.plot(t, sqr_wave,label='orig') sqr_wave_1st_order = signal.lfilter(b1, a1, sqr_wave) plt.plot(t, sqr_wave_1st_order,label='1st order') sqr_wave_4th_order = signal.lfilter(bt, at, sqr_wave) plt.plot(t, sqr_wave_4th_order,label='4th order ba') sos_4th_order = signal.butter(4,[7.692307692307693,13],'bandpass',fs=fs,output='sos') sqr_wave_sos = signal.sosfilt(sos_4th_order, sqr_wave) plt.plot(t, sqr_wave_sos,label='4th order sos') plt.ylim(-2, 2) plt.legend() plt.show() print(bt) print(at) Output: [ 4.82121714e-13 0.00000000e+00 -1.92848686e-12 0.00000000e+00 2.89273028e-12 0.00000000e+00 -1.92848686e-12 0.00000000e+00 4.82121714e-13] [ 1. -7.99560326 27.96927189 -55.90796275 69.84684949 -55.84709416 27.90840316 -7.96951656 0.99565219] [ 0.00083304 0. -0.00083304] To implement your SOS filter, you basically take your set of biquads (output of ouptut='sos') and stack the filters back to back. Julius Smith has a succinct explanation: https://ccrma.stanford.edu/~jos/fp/Series_Second_Order_Sections.html.
This is explained in this documentation page. In short, the function prefdir returns the path to where preferences are stored. In Linux this is ~/.matlab/<release>. It being a hidden directory explains why your find command didn’t find it. If you fail to find the right file where this configuration is stored in, you can always add your jenv command to your startup.m file. [Doesn't work in this case because changing the Java environment used requires restarting MATLAB.] In the preferences directory, there's a file called matlab.mlsettings. This is a ZIP file. Once unzipped, you'll find a JSON file at fsroot/settingstree/matlab/external/interfaces/java/maca64/settings.json (the maca64 part is for macOS, on Linux this will likely be glnxa64 instead of maca64). This JSON file has a bit that reads "name":"JrePath","value":"<path>" My guess is that you can edit the path there, zip up the directory again, and replace the original matlab.mlsettings file.
Your callback ```fileLoad1Callback``` doesn't know anything about the variables in ```selectLoad```. While you can assign characters to a struct ```fileLoad1.Text``` it doesn't do anything to your button. Inside ```fileLoad1Callback``` just replace ```fileLoad1.Text``` with ```src``` (which is your button object) and it should work.
How to import MATLAB datetime array into python?
Matlab/Simulink Parallel Computing with Initialization Scripts
You could take advantage of some thread/process management routines. Something along the lines of: % Create a thread pool pool = parpool('Threads'); % Submit the tasks to the thread pool future1 = parfeval(pool, @countToN, 0, 10); future2 = parfeval(pool, @countToN, 0, 1000); % Periodically check if any of the threads have finished while ~strcmp(future1.State,'finished') && ~strcmp(future2.State,'finished') pause(0.1); % Check every 100ms disp("checking stats") if strcmp(future1.State,'finished') fprintf('Task 1 finished, cancelling Task 2.\n'); future2.cancel(); elseif strcmp(future2.State,'finished') fprintf('Task 2 finished, cancelling Task 1.\n'); future1.cancel(); end end % Wait for both tasks to finish (in case they were cancelled) wait([future1, future2]); % Clean up the thread pool delete(pool); function countToN(n) for i = 1:n fprintf('Counting to %d: %d\n', n, i); pause(0.1); % 10ms delay end end
Note that `max(max(A))` for 2D `A` is more efficiently written as `max(A(:))`. In recent versions of MATLAB you can also do `max(A,[],'all')`.
The second factor inside the curly braces is missing a Fourier transform, isn't it?
How can I make the mean of 3d matrices in a cell in Matlab?
All your loop indices can change (by tiny amounts) when you change the end point. You might find this explanation interesting: https://stackoverflow.com/questions/49377234/how-does-the-colon-operator-work-in-matlab -- You should always use integers as loop indices, if you care about reproducibility and precision.
As I see it: Every numerical approach is always an approximation. And thus scaling the system *will* give different results. But still: The same way my, say, 4th-order-method will (up to a certain point) converge to the real solution with O(h^4) it should be possible to say: "If I scale down my system by a factor of 2, I will have to increase my relTol by X and my absTol by Y to get comparable results with comparable effort". All that of course only to a certain point (simulating masses that are lightyears apart over millions of years might fail because of cancellation if I *don't* scale down)
Are you wondering what would happen on a CPU with only E-cores, no P-cores, like Alder Lake N, or Xeon 6 Sierra Forest? Or a VM that had only E cores? IDK, hopefully it doesn't report 0 in that case :P
It is known that modern CPUs have both Performance cores (P-cores) and efficiency cores (E-cores), different types of CPU cores that have different purposes and are designed for different tasks. P-cores typically have higher clock speeds and designed for high-performance tasks, while E-cores operate at lower clock speeds and focus on energy-efficient processing. In MATLAB, maxNumCompThreads returns the current maximum number of computational threads. Currently, the maximum number of computational threads is equal to the number of physical cores on your machine. How MATLAB makes the distinction between P-Cores and E-Cores ? Brahim @ Singapore
The error you get is quite explicit, and tells you to try using str2sym: Error using sym&gt;convertChar (line 1557) Character vectors and strings in the first argument can only specify a variable or number. To evaluate character vectors and strings representing symbolic expressions, use 'str2sym'. Doing that gives us an output of 0, so we should heed the comment from Cris and use 10^ instead of 1e, as well as str2sym: x=str2sym('-10^(-10^308)') That gives us a different error: Error using str2sym (line 66) Unable to convert string to symbolic expression: Integer too large in context. This has already been asked about elsewhere Quoting the MathWorks staff member from the linked post: This error means the computation is trying to compute something like integer^integer with an exponent larger than 2^32. The resulting integer would take up several Gigabytes of memory and take a long time to compute – and be pretty much useless for virtually all applications. So the symbolic engine flat out refuses to start computing it. Aside: I would take a moment to consider if you actually require both exponents, that would be an incredibly tiny number (or large if the exponent sign was positive), even 10^(10^10) is large enough for the symbolic math engine to refuse creation...
You're passing a character array (the file name) to `size`. The actual file name you're using is probably 49 characters long. You probably want to use [`niftiread`](https://www.mathworks.com/help/images/ref/niftiread.html) to read your file and put the data in a variable. Then use that variable in the two places where you have the file name in your code.
In Matlab, I have given a network in the MATPOWER case file format (see the MATPOWER doc). I now want to check, if it is AC-feasible. To that end, I employed runpf (see the MATPOWER doc): define_constants; mpc = loadcase(case_file_path); results = runpf($mpc); On most of my cases, I got the result that it is feasible. Now I wanted to check the branch violations of the infeasible ones. However, I noticed that there are also branch violations on the ones that are marked as feasible (which for me does not make sense from a physical POV). I calculated the violations as follows: pfs = results.branch(:, PF); qfs = results.branch(:, QF); pts = results.branch(:, PT); qts = results.branch(:, QT); Sfs = sqrt(pfs.^2 + qfs.^2); Sts = sqrt(pts.^2 + qts.^2); active = mpc_target.branch(:, 11) &gt; 0.5; rates = mpc_target.branch(:, 6); % the 6th column gives the rateA of the branch violations_n = sum((Sfs .* active &gt; rates) | (Sts .* active &gt; rates)); My guess is that the function does not enforce the limits in the network, but that is what I need. What I tried so far: In the description of runpf it is mentioned, that the pf.enforce_q_lims option exists. I tried to set it to true (in the hope that this will somehow lead to an adherence of the flow limits as well), but the result remained unchanged. I found another function runcpf. This function DOES have the option cpf.enforce_flow_lims. However, the function seems to perform a continuation power flow, which I am guessing is not what I want since I need a base case and a target case (I am not an electrical engineer, so I have limited knowledge). Nevertheless, I ran the function (with both cases being the base case and the aforementioned option activated), but the result remained the same: the same violations occurr. I am unsure how to proceed. Is this simply not possible with MATPOWER due to restriction I am not aware of? This seems impractical to me however.
You're also setting `Q(i,:)=[k_1,k_1]` when there is only one instance of `i`, is that what you want? Will there ever be an instance where the two columns are different, or is `Q(:,1) == Q(:,2)`? Are all of the integers `[1:max(max(A))]` guaranteed to appear?
I have an inverse kinematics solver. I want to bias one joint angle value to at least approach a certain value wherein this angle will result in the link to be flat or parallel to the ground. The script runs well but my problem is fmincon stops the iteration, I think, once the default TolFun value is reached. The bias value is around +-0.17 radians or +- 10 degrees. I've tried using a very small TolFun value such as 1e-12 but it when an iteration converges, the angle I want to bias still does is not reach the desired value or close to it. I tried adding an fval threshold and using while loop but I think the TolFun stopping criterion still supersedes that since whan I run the script, almost similar convergence are reached. I need some help in how to implement the biasing. Here is the code snippet: function A = transformation_matrix(theta, alpha, a, d) A = [[cos(theta), -cos(alpha) * sin(theta), sin(alpha) * sin(theta), a * cos(theta)]; [sin(theta), cos(alpha) * cos(theta), -sin(alpha) * cos(theta), a * sin(theta)]; [0, sin(alpha), cos(alpha), d]; [0, 0, 0, 1]]; end function position = forward_kinematics(joint_angles) theta2 = joint_angles(1); theta3 = joint_angles(2); theta4 = joint_angles(3); theta5 = joint_angles(4); theta6 = joint_angles(5); A1 = transformation_matrix(0, 0, 0, 148); A2 = transformation_matrix(theta2, pi/2, 0, 152); A3 = transformation_matrix(theta3, 0, 250, 0); A4 = transformation_matrix(theta4, 0, 160, 0); A5 = transformation_matrix(theta5+pi/2, pi/2, 0, 0); A6 = transformation_matrix(theta6, 0, -75, 160); position_matrix = A1 * A2 * A3 * A4 * A5 * A6 * [0; 0; 0; 1]; %threshold = 1e-8; % Small threshold to round off to zero %position_matrix(abs(position_matrix) &lt; threshold) = 0; % Set small values to zero position = position_matrix(1:3); end function error = objective_function(joint_angles, target, initial_guess, is_first_run) theta3 = joint_angles(2); theta4 = joint_angles(3); theta5 = -(theta3+theta4); position = forward_kinematics(joint_angles); error = norm(position - target); bias_theta5=abs(joint_angles(4)-theta5); disp('Theta 5 bias:'); disp(bias_theta5); error += 1*bias_theta5 %bias to land theta5 close to a value that parallel with the origin Y-coord if ~is_first_run error += 0.1 * norm(joint_angles - initial_guess); % Penalize deviation from initial guess end end function error = objective_function(joint_angles, target, initial_guess, is_first_run) theta3 = joint_angles(2); theta4 = joint_angles(3); theta5 = -(theta3 + theta4); position = forward_kinematics(joint_angles); error = norm(position - target); bias_theta5 = abs(joint_angles(4) - theta5); disp('Theta 5 bias:'); disp(bias_theta5); error += 1 * bias_theta5; % Bias to land theta5 close to the value parallel with the origin Y-coord if ~is_first_run error += 0.1 * norm(joint_angles - initial_guess); % Penalize deviation from initial guess end end function [joint_angles, exitflag] = inverse_kinematics(target_position, initial_guess, is_first_run) options = optimset('Display', 'final', 'MaxIter', 2000); % Omitting 'TolFun' % Constraints for initial values for the first four angles initial_lb = [-(5/6) * pi; -(1/6) * pi; -(11/18) * pi; -(1/2) * pi]; initial_ub = [ (5/6) * pi; (5/9) * pi; 0; (1/2) * pi]; if is_first_run lb = initial_lb; % Use the initial lower bounds ub = initial_ub; % Use the initial upper bounds else % Update bounds based on the converged joint angles lb = initial_lb - initial_guess(1:4); % Subtract converged values ub = initial_ub - initial_guess(1:4); % Subtract converged values end initial_guess_4 = initial_guess(1:4); %max_iter = 100; % Set a maximum number of iterations fval_threshold = 0.17; % Stopping criterion for fval iter = 0; converged = false; while ~converged %&amp;&amp; iter &lt; max_iter % Optimize theta2, theta3, theta4 [joint_angles_4, fval, exitflag] = fmincon(@(j) objective_function([j; 0], target_position, initial_guess, is_first_run), ... initial_guess_4, [], [], [], [], lb, ub, [], options); % Check the stopping criterion based on fval if fval &lt; fval_threshold converged = true; % We have reached the desired fval end initial_guess_4 = joint_angles_4; % Update initial guess for next iteration %iter = iter + 1; end joint_angles = [joint_angles_4; 0]; % Set theta 6 to zero % Display result if converged fprintf('Converged with fval: %f\n', fval); else fprintf('Maximum iterations reached without achieving desired fval.\n'); end end
RTW Embedded coder generating #includes in C file instead of H file
The missing `from` was my bad, I was trying to anonymize the query a bit and deleted that.
Im trying to plot a Airfoil using matlab and want a sharp edge but i cant figure it out
Load Flow Analysis Issue in IEEE 34-Bus Model on MATLAB Simulink
Is there an aggregate array function in Matlab similar to reduce in Google Sheet or foldr in Racket? For example, the other day, I was hoping to extract/exclude a row representing every third week of the month, isnumeric() =&gt; true isnumeric() =&gt; true 202211 data_to_be_aggregated_type_1 202211 data_to_be_aggregated_type_1 202211 data_to_be_aggregated_type_2 202211 data_to_be_aggregated_type_1 202211 data_to_be_aggregated_type_1 202212 data_to_be_aggregated_type_1 202212 data_to_be_aggregated_type_1 202212 data_to_be_aggregated_type_2 202212 data_to_be_aggregated_type_1 I ended up copying the data to Google Sheet, where the data can be processed with one (local) function, and only then copied to Matlab As well, in the above example, it is necessary(?) to be able to reference a different index based on a preset offset from the current index. In order to tell whether a row represents the 3rd week of a month, one way is to, for example, check whether month digits are different from 3 rows before but the same as 2 rows before. Google Sheet allows for this via offset. (Google Sheet reduce also only accepts 1D array as argument, further increasing the need for offset.) So.. Is there an Matlab equivalent for reduce or foldr and the corresponding tools such as offset?
The error message is pretty clear about the solution: “Please install the correct version of the MATLAB Runtime.” [The documentation for MATLAB Compiler](https://www.mathworks.com/help/compiler/index.html) is also pretty clear: “End users can run your applications royalty-free using MATLAB Runtime.” See here for more information on the runtime: https://www.mathworks.com/help/compiler/matlab-runtime.html
How can I find the row reduced form of a symbolic matrix with matlab. I have the symbolic toolkit installed and looking at the documentation it says to just use the rref function like normal. However, this doesn't seem to work properly. Example syms h M = [ 1 h 2 3] rref(M) This results in [1, 0] [0, 1] However I would expect the answer to be closer too [1, h] [0, 3-2*h] How do I do this? Other operations (add, subtract, det) work fine with symbolic matrices. Is there a different command to use? Or is this just not possible? Thanks
The link to access the Excel file is now working.
@LuisMendo added, `im2col` is curiously noisy too compared to the other methods - added to the benchmark above
Is "some number" the same for all entries that need to be modified? If not, what is the rule to compute that number?
Hi Cris, this is a minimum reproducible example, which generates the test data, runs the analysis, then plots the outputs, including the linear discriminant for reference. Whilst there's no error code, the issue is clear, the boundaries between the groups just aren't present on figure 2. So, something is wrong with how I'm plotting figure 2, at the very end of the code sample. Could be as simple as "evaluating the coeffs incorrectly", which was the issue with the 3d question I posted, but I can't for the life of me figure out how to correct it for this.
I was reluctant to take the last approach since it involves learning a new tool and integrating it into my CI Pipeline, but I'm now thinking its the best option. I have about 30 functions.
In my case T was of shape (height,width,numClasses,batchSize, so I had to change T==i to T(:,:,i,:). Other than that, it worked perfectly
Glad I could help for such a beautiful application!
ID Channel relativeAlpha relativeBeta relativeGamma 01-12 F7 9.25 1.23 2.98 01-12 F8 8.35 3.45 6.78 I'm using EEG lab to calculate relative spectral power for various bands. This went well, but now I'm stuck on how to reshape this the way I need it. I have 20 participants, and I want each participant to have only one row of data. As such, I'm trying to convert this matrix so that the columns are a combination of electrode and frequency band. For example, each participant would have one row of data with columns labelled F7.relativeAlpha, F7.relativeBeta, and so on (see below for example). Any help would be greatly appreciated! ID F7.relativeAlpha F7.relativeBeta F7.relativeGamma F8.relativeAlpha F8.relativeBeta F8.RelativeGamma 01-12 9.25 1.23 2.98 8.35 3.45 6.78 I've tried unsuccessfully with the reshape function and with the unstack function. RelativePowerWide = unstack(RelativePowerResults,'ID','RelativeDelta')
I have a data table with three columns: t = [ datum,meter-reading,meter-exchange 25-Sep-2012,2.6,0 13-Oct-2013,12.0,0 28-Oct-2013,14.4,0 01-Nov-2013,14.2,1 12-Dec-2013,0.1,0 23-Feb-2014,0.9,0 15-Jun-2014,3.0,0 15-Sep-2014,6.0,0 23-Jun-2015,8.7,0 06-Oct-2015,10.2,0 ... ] Is there any neat way to create a new table (matrix) where the yearly consumption is calculated with the meter-readings including possible meter changes (meter exchanged "1" in column 3). The consumption is calculated by the difference of the latest meter reading in one year and the latest meter reading in the year before. But when the meter is exchanged the consumption is calculated slightly differently (if change is "1", take difference from the meter reading of that date with last meter reading of the year before plus the last meter reading of the same year. Expected result is (ignoring first year 2012): t1 = [ year,consumption 2013,11.7 2014,5.9 2015,4.2 ... ]
MATLAB Neural Network Predictions Converging to 1
It seems that in outerFunc(innerFunc, [2, 4, 5]) % doesn't work you intend to pass innerFunc as an input to outerFunc. However, what that line does is call innerFunc (which gives an error because the input to that function is missing); and the output of that function call would then be used as input to outerFunc. To pass (a handle of) innerFunc as an input to outerFunc you need to prepend @ (more information here): outerFunc(@innerFunc, [2, 4, 5])
@ThomasIsCoding, I don’t have access to MATLAB at the moment to try it, but could you try the effect of making the bottom-right element of the matrix 0.57735027-0.5j (i.e. non-zero imaginary part) and see if that would give the vector that the OP writes for MATLAB. This is what a hand calculation suggests might be the original fault.
=== Simulation (Elapsed: 3 sec) === pulse = 1 Error:An error occurred while running the simulation and the simulation was terminated Caused by: Derivative of state '1' in block 'chargecontrol/PV Array/Diode Rsh/Transfer Fcn' at time 0.0 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances) I tried to change the tolerance sample time but it did not work and I tried a constant DC source and it is working. I have put the irradiation and temperature constant too.
I am translating a MATLAB script that performs spectral factorization into R using the CVXR package for convex optimization. I have simplified the problem to focus only on constructing the Q matrix while maintaining the core constraints and objective. MATLAB Script The following MATLAB script constructs the Q matrix using a convex optimization framework: The Constraints Q must be positive semi-definite. The block diagonals of Q are constrained to match the elements of R. Specifically, for every lag k (from 0 to p), the constraints ensure that the trace of each block matches the corresponding block of R. function Q = compute_Q(n, p, Y) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %input: % n = number of variables % p = order of the true AR model % Y = causal part of the "true" matrix polynomial $S^{-1}$ (IS) %output: % Q = symmetric positive semidefinite matrix satisfying the constraints %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% R = Y; s = n * (p + 1); cvx_begin quiet variable Q(s, s) symmetric; maximize trace(Q(1:n, 1:n)); subject to Q == semidefinite(s); for k = 0:p ind_diag = diag(ones(p + 1 - k, 1), k); for i = 1:n for j = 1:n ind_bl = zeros(n); ind_bl(i, j) = 1; trace(kron(ind_diag, ind_bl) * Q) == R{k + 1}(i, j); end end end cvx_end end Problem Objective: Maximize the trace of the top-left nxn block of Q, i.e., maximize trace(Q_{1:n,1:n}). Constraints: Q >= 0 (positive semidefinite constraint). trace(kron(ind_diag, ind_bl)xQ) = R_{ij}^{k}, where: ind_diag: A diagonal matrix defining the block structure for lag k. ind_bl: A block matrix with a single nonzero element at position (i,j). R Translation I translated the above MATLAB script into R using the CVXR package: library(CVXR) compute_Q <- function(n, p, Y) { R <- Y s <- n * (p + 1) Q <- Variable(s, s, symmetric = TRUE) # Objective: Maximize trace of the top-left block of Q objective <- Maximize(sum(diag(Q[1:n, 1:n]))) # Constraints: Q is positive semidefinite constraints <- list(Q %>>% 0) # Add trace constraints for each block for (k in 0:p) { ind_diag <- diag(rep(1, p + 1 - k), k) for (i in 1:n) { for (j in 1:n) { ind_bl <- matrix(0, n, n) ind_bl[i, j] <- 1 constraints <- c( constraints, trace(Q %*% kronecker(ind_diag, ind_bl)) == Rk + 1[i, j] ) } } } # Solve the problem problem <- Problem(objective, constraints) result <- solve(problem, solver = "SCS") # Return the computed Q matrix return(result$getValue(Q)) } Inputs The inputs for the R function are: k <- 9 n <- 5 p <- 1 Y <- list( matrix(c(2.1983699, 0.2066341, 0.2048484, 0.2066970, 0.2011900, 0.2066341, 2.1954148, 0.2043585, 0.1901186, 0.1995567, 0.2048484, 0.2043585, 2.2169782, 0.2075691, 0.2009464, 0.2066970, 0.1901186, 0.2075691, 2.2021540, 0.2096051, 0.2011900, 0.1995567, 0.2009464, 0.2096051, 2.1970326), nrow = 5, byrow = TRUE), matrix(c(0.1849041, 0.2060889, 0.1936582, 0.2057210, 0.2185530, 0.1942851, 0.2074143, 0.1904800, 0.1798709, 0.2280653, 0.1866000, 0.1944861, 0.1887652, 0.1946746, 0.1985805, 0.2231732, 0.1974313, 0.2047517, 0.1884571, 0.1967431, 0.2076642, 0.2123295, 0.1948372, 0.2092436, 0.1989898), nrow = 5, byrow = TRUE) ) Error Encountered When I run the R function: Q_result <- compute_Q(n, p, Y) I get the following error: Error in .local(.Object, ...) : Invalid dimensions 00 17. stop("Invalid dimensions ", dim) 16. .local(.Object, ...) 15. .nextMethod(.Object, ..., dim = intf_dim(.Object@value)) 14. eval(call, callEnv) 13. eval(call, callEnv) 12. callNextMethod(.Object, ..., dim = intf_dim(.Object@value)) 11. .local(.Object, ...) 10. initialize(value, ...) 9. initialize(value, ...) 8. new(structure("Constant", package = "CVXR"), ...) 7. .Constant(value = value) 6. Constant(value = expr) 5. as.Constant(y) 4. Q %*% kronecker(ind_diag, ind_bl) 3. Q %*% kronecker(ind_diag, ind_bl) 2. trace(Q %*% kronecker(ind_diag, ind_bl)) 1. compute_Q(n, p, Y) Question Why does the CVXR implementation fail with this "Invalid dimensions" error? How should the constraints be set up in R to correctly mimic the MATLAB constraints?
Your MATLAB result doesn’t match OP’s leading me to think OP didn’t compute their result in same way you did. They likely had a different input matrix as suggested by the other answer.
How to Use MATLAB's RL Toolbox to Build a Reinforcement Learning Agent for Controlling PID Parameters in Track Control?
Gazebo sim not starting because of undefined symbol from libQt5Quick.so.5
I do not think Matlab will allow excel to run inside a compiled script. Talk to Matlab.
And surely you checked that you’re running the same Python installation in VSCode and in MATLAB. Have you tried using `system(‘python Merger_CT_X_TARGET_Y.py')`?
@user2587726 yes you can replace the 6 lines in your code which define `f12,f23,f13,h2,h3,h4` exactly with the 6 lines I've provided above (note they are different!) and include the additional local function in your code, and it should work the same with `fimplicit3`. The only change I've made is defining the function given to the implicit plotting differently so that it works for 3D coordinates.
Actually, boundary does not work in Matlab as I know...
Different result in Matlab and Python for StateSystem
I have no idea how the backslashes ended up there. I was struggling to insert code since this was my first time asking a question, so I’m pretty sure I messed something up. The code is from MATLAB. I’ve fixed it now, thank you!
Does Matlab clear the plot before each new update or does it accumulate?
Add Additional Legends for Specific Bar Colors in MATLAB Bar Chart
(1) Do you really need a cell array of cell arrays? It would be much easier if you stored the numbers in a numeric 2D or 3D array, or if you convert into that. (2) Is the result correct? For example, how is `33` obtained? (3) What type of array do you need the result to be? What you show is 5 separate arrays.
My nightmares with discriminant analysis continue... Trying to plot the "one dimensional" quadratic discriminant analysis, where the discriminant is only being decided on by the x-axis. It works fine for linear (as shown in the code sample) but I can't get the quadratic (aka curved) boundaries to plot correctly. I've tried a few things (all in the code sample) to no avail. I think the issue is with what I'm passing to the implicit function, when I had problems with the 3D case this was the solution, but I just don't understand how to fix it myself. I have noticed that Qxx(1,2) = -1*Qxx(2,1), but not sure how that contributes to the issue. clear clc close all %---------------------------- x1 = 1:0.01:3; r = -1 + (1+1)*rand(1,201); x1 = x1 + r; y1 = 1:0.01:3; r = -1 + (1+1)*rand(1,201); y1 = y1 + r; x1 = x1'; y1 = y1'; label1 = ones(length(y1),1); Tclust1 = [label1,x1,y1]; %---------------------------- x2 = 7:0.01:9; r = -1 + (1+1)*rand(1,201); x2 = x2 + r; y2 = 10:0.01:12; r = -1 + (1+1)*rand(1,201); y2 = y2 + r; x2 = x2'; y2 = y2'; label2 = 2.*ones(length(y2),1); Tclust2 = [label2,x2,y2]; %---------------------------- x3 = 15:0.01:17; r = -1 + (1+1)*rand(1,201); x3 = x3 + r; y3 = 13:0.01:15; r = -1 + (1+1)*rand(1,201); y3 = y3 + r; x3 = x3'; y3 = y3'; label3 = 3.*ones(length(y3),1); Tclust3 = [label3,x3,y3]; %---------------------------- T = [Tclust1;Tclust2;Tclust3]; data = T(:,2:3); labels = T(:,1); %LOOCV n = length(labels); hpartition = cvpartition(n,'leaveout'); % figure() output = zeros(n,3); for qq = 1:n %training data idx_Train = training(hpartition,qq); data_Train = data(idx_Train,1:2); labels_Train = labels(idx_Train); %test data idx_Test = test(hpartition,qq); data_Test = data(idx_Test,1:2); labels_Test = labels(idx_Test); %train the model on the training data Mdlquad = fitcdiscr(data_Train,labels_Train,'Discrimtype','quadratic'); %apply to the testing data pred_lbl = predict(Mdlquad,data_Test); (qq/n)*100 end iscorrect=output(:,1)==output(:,2); accuracy_full = (sum(iscorrect)/length(iscorrect))*100; %get coeffs K12 = Mdlquad.Coeffs(1,2).Const; L12 = Mdlquad.Coeffs(1,2).Linear; Q12 = Mdlquad.Coeffs(1,2).Quadratic; K23 = Mdlquad.Coeffs(2,3).Const; L23 = Mdlquad.Coeffs(2,3).Linear; Q23 = Mdlquad.Coeffs(2,3).Quadratic; K13 = Mdlquad.Coeffs(1,3).Const; L13 = Mdlquad.Coeffs(1,3).Linear; Q13 = Mdlquad.Coeffs(1,3).Quadratic; %plot data with boundaries ----------------------------------------------- data = T(:,2:3); labels = T(:,1); xmin = min(T(:,2)); xmax = max(T(:,2)); ymin = min(T(:,3)); ymax = max(T(:,3)); %plot linear... figure() scatter(x1,y1,'g') hold on scatter(x2,y2,'b') scatter(x3,y3,'r') title('Linear = correct') xlabel('variable') ylabel('control') %legend('Data 1','Data 2','Data 3','Boundary 1 -> 2','Boundary 2 -> 3','Boundary 1 -> 3','location','eastoutside') %group 1 and group 2 f12 = @(x1,x2) K12 + L12(1)*x1 + L12(2)*x1; h2 = fimplicit(f12,[xmin xmax ymin ymax],'--g'); %group 2 and group 3 f23 = @(x1) K23 + L23(1)*x1+ L23(2)*x1; h3 = fimplicit(f23,[xmin xmax ymin ymax],'--r'); %group 1 and group 3 f13 = @(x1) K13 + L13(1)*x1+ L13(2)*x1; h4 = fimplicit(f13,[xmin xmax ymin ymax],'--b'); %plot quadratic... figure() scatter(x1,y1,'g') hold on scatter(x2,y2,'b') scatter(x3,y3,'r') title('Quadratic = Problematic') xlabel('variable') ylabel('control') %legend('Data 1','Data 2','Data 3','Boundary 1 -> 2','Boundary 2 -> 3','Boundary 1 -> 3','location','eastoutside') %group 1 and group 2 f12 = @(x1) K12 + Q12(1)*x1.^2 + Q12(2)*x1.^2 + Q12(3)*x1.^2+ Q12(4)*x1.^2; h2 = fimplicit(f12,[xmin xmax ymin ymax],'--g'); %group 2 and group 3 f23 = @(x1) K23 + Q23(1)*x1.^2 + Q23(2)*x1.^2 + Q23(4)*x1.^2; h3 = fimplicit(f23,[xmin xmax ymin ymax],'--r'); %group 1 and group 3 f13 = @(x1) K13 + Q13(1)*x1.^2 + (Q13(2)+Q13(3))*x1.^2 + Q13(4)*x1.^2; h4 = fimplicit(f13,[xmin xmax ymin ymax],'--b');
You can configure your batch script to automatically elevate itself when executed, ensuring you never "forget" it needs sufficient privileges for its operations. Place this code as early as possible in your batch script (usually after @echo off, setlocal, and a basic argument check, so elevation isn't requested unnecessarily, such as when only displaying help syntax): REM Check admin mode and auto-elevate if required openfiles > NUL 2>&1 || ( REM Not elevated - perform elevation echo createObject^("Shell.Application"^).shellExecute "%~dpnx0", "%*", "", "runas">"%TEMP%\%~n0.vbs" cscript /nologo "%TEMP%\%~n0.vbs" goto :eof ) del /s /q "%TEMP%\%~n0.vbs" > NUL 2>&1 Explanation: The basic idea is to check if the script is already elevated using a command like openfiles, in "mute mode", which requires elevated privileges to run. If it fails, the || operator triggers the auto-elevation sequence. Creating VBScript Dynamically: A temporary VBScript file is created on-the-fly. It uses shellExecute with the runas parameter to relaunch the batch script with elevation. %~dpnx0 represents the current batch script, while %* forwards any original command-line arguments. Executing Elevation: The VBScript runs without elevation, but it prompts for elevation before executing the batch script. The original batch exits immediately using goto :eof. Returning to Elevated Script: When the elevated batch restarts, the openfiles command succeeds, skipping the elevation block. The temporary VBScript file is deleted, and the batch script proceeds in the elevated environment. Limitation: A major drawback of this method is that shellExecute does not allow waiting for the elevated process to finish. This means: ShellExecute: Elevate easily but lose control over the batch script's execution. Run: Control execution but cannot handle elevation automatically. Workarounds: Active Waiting: Poll the process in a loop to check if it has completed, but this risks missing short-lived processes. Advanced Win32 API: Use more sophisticated solutions leveraging the Win32 API, which are more complex to implement in a batch script. Unfortunately, a straightforward solution that combines automatic elevation and precise control isn't readily available in batch scripting.
Jumped right in and posted the next question! https://stackoverflow.com/questions/79291579/one-dimensional-quadratic-discriminant-analysis-in-matlab
I have seen in the Mathworks official website for the pixelClassificationLayer() function that I should update it to a custom loss function using the following code: function loss = modelLoss(Y,T) mask = ~isnan(T); targets(isnan(T)) = 0; loss = crossentropy(Y,T,Mask=mask,NormalizationFactor="mask-included"); end netTrained = trainnet(images,net,@modelLoss,options); However, I can't see any mention of the inputs 'Classes' or 'ClassWeights', which I'm currently using to define the custom pixelClassificationLayer: pixelClassificationLayer('Classes',classNames,'ClassWeights',classWeights), where classNames is a vector containing the names of each class as a string and classWeights is a vector containing the weights of each class to balance classes when there are underrepresented classes in the training data. How can I include these parameters in my custom loss function?
Yes, I even looked at the worked examples: https://au.mathworks.com/help/stats/create-and-visualize-discriminant-analysis-classifier.html `f = @(x1,x2) K + L(1)*x1 + L(2)*x2 + Q(1,1)*x1.^2 + (Q(1,2)+Q(2,1))*x1.*x2 + Q(2,2)*x2.^2; h2 = fimplicit(f,[.9 7.1 0 2.5]); h2.Color = 'r'; h2.LineWidth = 2; h2.DisplayName = 'Boundary between Versicolor & Virginica';` However this example is using x1 and x2, where as I only want to use x1.
I have a system where a car's position is adjusted using PID control, and the car moves along a road with several measurement points (x, y coordinates). I want to improve the precision of the PID controller using a reinforcement learning (RL) agent. I referred to the MATLAB example "Tune PI Controller Using Reinforcement Learning" for guidance. The challenge I’m facing now is how to implement my system in Simulink. The model training should follow a similar approach to the example, but I am unsure how to structure the Simulink model to integrate the RL agent for controlling the PID parameters. Any advice or steps to help with this integration would be much appreciated! Here is the code and model I refer to and how I should modify it. Reinforcement learning model of water tank system open_system('watertankLQG'); Ts = 0.1; Tf = 10; controlSystemTuner("ControlSystemTunerSession"); Kp_CST = 9.80199999804512; Ki_CST = 1.00019996230706e-06; mdl = 'rlwatertankPIDTune'; open_system(mdl); [env,obsInfo,actInfo] = localCreatePIDEnv(mdl); numObs = prod(obsInfo.Dimension); numAct = prod(actInfo.Dimension); rng(0); initialGain = single([1e-3 2]); actorNet = [ featureInputLayer(numObs) fullyConnectedPILayer(initialGain,'ActOutLyr') ]; actorNetGraph = layerGraph(actorNet); actorNet = dlnetwork(actorNetGraph); actor = rlContinuousDeterministicActor(actorNet,obsInfo,actInfo); criticNet = localCreateCriticNetwork(numObs,numAct); criticNetGraph = layerGraph(criticNet); critic1 = rlQValueFunction(dlnetwork(criticNetGraph), ... obsInfo,actInfo,... ObservationInputNames='stateInLyr', ... ActionInputNames='actionInLyr'); critic2 = rlQValueFunction(dlnetwork(criticNetGraph), ... obsInfo,actInfo,... ObservationInputNames='stateInLyr', ... ActionInputNames='actionInLyr'); critic = [critic1 critic2]; actorOpts = rlOptimizerOptions( ... LearnRate=1e-3, ... GradientThreshold=1); criticOpts = rlOptimizerOptions( ... LearnRate=1e-3, ... GradientThreshold=1); agentOpts = rlTD3AgentOptions(... SampleTime=Ts,... MiniBatchSize=128, ... ExperienceBufferLength=1e6,... ActorOptimizerOptions=actorOpts,... CriticOptimizerOptions=criticOpts); agentOpts.TargetPolicySmoothModel.StandardDeviation = sqrt(0.1); agent = rlTD3Agent(actor,critic,agentOpts); maxepisodes = 1000; maxsteps = ceil(Tf/Ts); trainOpts = rlTrainingOptions(... MaxEpisodes=maxepisodes, ... MaxStepsPerEpisode=maxsteps, ... ScoreAveragingWindowLength=100, ... Verbose=false, ... Plots="training-progress",... StopTrainingCriteria="AverageReward",... StopTrainingValue=-250); doTraining = true; if doTraining % plot(env); % Train the agent. trainingStats = train(agent,env,trainOpts); else % Load pretrained agent for the example. load("WaterTankPIDtd3.mat","agent") end simOpts = rlSimulationOptions(MaxSteps=maxsteps); experiences = sim(env,agent,simOpts); actor = getActor(agent); parameters = getLearnableParameters(actor); Ki = abs(parameters{1}(1)) Kp = abs(parameters{1}(2)) mdlTest = 'watertankLQG'; open_system(mdlTest); set_param([mdlTest '/PID Controller'],'P',num2str(Kp)) set_param([mdlTest '/PID Controller'],'I',num2str(Ki)) sim(mdlTest) rlStep = simout; rlCost = cost; rlStabilityMargin = localStabilityAnalysis(mdlTest); set_param([mdlTest '/PID Controller'],'P',num2str(Kp_CST)) set_param([mdlTest '/PID Controller'],'I',num2str(Ki_CST)) sim(mdlTest) cstStep = simout; cstCost = cost; cstStabilityMargin = localStabilityAnalysis(mdlTest); figure plot(cstStep) hold on plot(rlStep) grid on legend('Control System Tuner','RL',Location="southeast") title('Step Response') Any suggestions on how to approach this, or references to similar examples, would be greatly appreciated. Also, if anyone has any resources or insights on implementing this in Simulink, I would be thankful for your help!
Looks good! Can I have some more info please? Once you've made fKLQ, how have you plotted it? With fimplicit3 still?
Inputting variables when running python code in MATLAB using system
Hi, Till, many thanks for your answer, and yes, this is exactly what I was expecting. I was able to implement it into the analyses code! One thing I am worried about is making it work for other maps that have angled paths so it's not exactly a simple rectangle shape.
Does [this](https://stackoverflow.com/questions/53742906/how-do-i-sign-the-installed-executable-of-a-compiled-matlab-program) answer your question?
Very nice answer, I wonder how would this look like in comparison with a code I wrote for error propagation in [python](https://stackoverflow.com/a/79174716/16815358). Might check it out and post a question in case something does not check out :D
slprj is a folder created by Simulink for storing model artifacts. You can create src and include directories for your own files. include directory typically contains header files for declarations. tmwtypes.h is part of MATLAB. You do not need to include it.
Find below a solution, may be not the best one [c,k]=gsort(c,'r','i'); i=find(c(1:$-1,1)&lt;&gt;c(2:$,1)); r=[];l=1; for j=[i(1:$),size(c,1)] r=[r;c(j,1),sum(c(l:j,2))]; l=j+1; end
Matlab Convert Stuct of Nodes to Node Array
How do I track the states from a discrete state space block?
The issue with ylabel being cut off usually occurs due to the figure layout and tight boundaries. You can resolve this by adjusting the axes and fig properties. You can move the xlabel closer to the xticks by adjusting its position manually. I believe this code here should solve your problems for showing ylabel fully and moving the xlabel closer to the xticks: clear; % Change default axes fonts. set(0,'DefaultAxesFontName', 'Times New Roman') set(0,'DefaultAxesFontSize', 21) % Change default text fonts. set(0,'DefaultTextFontname', 'Times New Roman') set(0,'DefaultTextFontSize', 21) % Define data x = [100, 200, 300, 400, 500]; data = [ 5.3, 7.3, 4.3, 3.3, 1.3; 4.3, 4.3, 4.3, 5.3, 10.3; 2.3, 7.3, 2.3, 8.3, 2.3; 1.3, 9.3, 8.3, 7.3, 0.3; 9.3, 2.3, 0.3, 2.3, 0.3; 6.3, 7.3, 9.3, 6.3, 7.3; ]; datasetNames = {'A', 'B', 'C', 'D', 'E', 'F'}; % Create a 3D bar chart figure; bar3(data); % Customize the axes set(gca, 'XTickLabel', x, 'YTickLabel', datasetNames, 'FontSize', 21); % Set x-axis labels as number of tasks % Align labels xlh = xlabel('Task Count', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', -30); ylh = ylabel('Method', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', 37); zlh = zlabel('Fitness', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal'); % Adjust position of the xlabel to bring it closer to xticks xlh.Position(2) = xlh.Position(2) - 1; % Adjust the vertical position as needed % Adjust axes properties to make ylabel fully visible set(gca, 'Position', [0.2, 0.2, 0.6, 0.6]); % Modify axes position within the figure outerpos = get(gca, 'OuterPosition'); % Get current outer position ti = get(gca, 'TightInset'); % Get tight inset for padding set(gca, 'Position', [outerpos(1) + ti(1), outerpos(2) + ti(2), ... outerpos(3) - ti(1) - ti(3), outerpos(4) - ti(2) - ti(4)]); % Adjust for tight layout % Set Z-axis limits zlim([0.31, max(data(:))]); % Start Z-axis at 0.31 % Set view angle for better visualization view(45, 30); % Adjust figure size and layout set(gcf, 'Units', 'normalized', 'Position', [0.2, 0.2, 0.6, 0.6]); % Adjust paper size for saving fig = gcf; fig.PaperUnits = 'centimeters'; fig.PaperPosition = [0 0 14.4 12.4]; fig.PaperSize = [13.4 11.5]; % width &amp; height of page % Save the figure print('FST_D_S2.pdf','-dpdf','-r1200'); I may have missed something. If so, I will edit the post.
App designer generated app freezes when I run the code
If you are just after extracting words at the start of a line before a `=`, use `^\s*([a-zA-Z_]\w*)\s*=`
R: Error Running Convex Optimization With CVXR
I am working with a SQLite database in MATLAB and trying to insert NULL values into some fields of a table. However, MATLAB throws an error when I attempt to insert NULL. Here's an example: % Define the SQLite database file name dbFileName = 'example.db'; % Delete the database file if it exists if exist(dbFileName, 'file') == 2 delete(dbFileName); end % Connect to the SQLite database conn = sqlite(dbFileName, 'create'); % Create a sample table createTableQuery = [ ... 'CREATE TABLE example_table (' ... 'id INTEGER PRIMARY KEY, ' ... 'name TEXT, ' ... 'age INTEGER DEFAULT NULL' ... ')']; exec(conn, createTableQuery); % Insert data with a NULL value for the 'age' field insert(conn, 'example_table', {'id', 'name', 'age'}, {1, 'John', []}); % Close the database connection close(conn); When I run this code, MATLAB throws the following error: Error using sqlite/insert Inconsistent row counts for column 0 (1) and column 2 (0). Error in test (line 22) insert(conn, 'example_table', {'id', 'name', 'age'}, {1, 'John', []}); If I replace [] with 0, the insertion works, but this is not a true NULL value. How can I insert actual NULL values into a SQLite database table using MATLAB? Is there a specific syntax or workaround for this?
@ticktalk I guess you were a bit faster than me there :D
I'm trying to add a C caller block in Simulink so I can add my own C functions to a Simulink Model. I have referred to a built in example in Matlab which, called 'CallCFunctionsUsingCCallerBlockExample'. This contains 3 folders, called 'include', 'slprj' and 'src'as well as some files, such as the slx file which defines the model. The main problems I have are when attempting to specify Include directories in the Simulate Target section of Model Properties, I am not sure how to make the Include folder. Presumably it's not just going to be the same one as in their example, or is it? If not, how do I know which files to put in this folder and what they need to have in? This doesn't seem to be explained in the Matlab Help section on using C caller blocks. knowing which folders to have in my Matlab model directory. Do I need to include the slprj and src files, together with their contents and do these need to be the same as in their example? If not, how do I know what to put in them? additionally, their C file which defines the C functions used in the model (myfunc.c) refers to 2 files at the start with the lines #myfunc.h and #tmwtypes.h. Whilst I can see where myfunc.h is in the directory and I understand what it does, which is to declare the C functions defined in myfunc.c, I can't see where tmwtypes.h is. Do I need it and again, if so, is it going to be the same as for their example and if not, how can I find out what needs to be in it?
Thanks..yes, the print statements appear in Matlab, as coded in python, so there is no problem with that. This is a really strange problem, because i dont see any reasons why this return values are not properly given back from Matlab, and this code is not complicated or advanced in any case
Error installing matlabengine in conda environment
Opened `m2cpp.pl` in Vim inside of the container and it is indeed full of `^M` characters so will start thinking about a fix on monday.
I'm looking to read a large number of nodes from an OPC_UA server using [val] = readValue(uaClient,read_nodes_test) For tidiness sake, i've got my nodes stored in a struct which i've called OPC_UA_nodes. The issue is i cannot find a way to convert this struct of nodes to the node array required for the readvalue command. All documentation encourages me to use struct2cell and then cell2mat, however cell2mat does not support cell arrays containing cell arrays or objects. What is the best way to create the node array? Besides nodes = [node1, node2, node3,..., node75]
Both matlab and scipy are well-tested pieces of software and I doubt that either is giving wrong or inaccurate results. The problem is almost certainly with your input. You really need to show the code that produced those results. I don't think what you have posted here is the matrix that you have input to matlab. Actually - see below - I suspect they differ in the element at the bottom right-hand corner. EDIT: I think the version you sent to matlab had imaginary part -0.5j, whereas the version given to scipy involved just 0.j. The real part is OK. Your scipy.null_space vector correctly gives 0 when multiplied by the given matrix A; your matlab vector doesn't ... for that matrix. Given that the matrix is in reduced-row-echelon form and has rank 3, it is not that difficult to work out, to within an arbitrary unit-magnitude complex factor, a single-vector generator for the null space by hand. The ratio of elements in the two solutions is a constant (complex) number, except for the third row. This would arise if the matrices sent to scipy.null_space and to matlab differ in a single element in the bottom right-hand corner. The scipy.null_space vector is correctly normalised to 1. I doubt that either piece of software is faulty. I think you should check that you have the same matrix in both codes. import numpy as np A = np.array( [ [ 1.+0.j, 0.+0.j, 0.+0.j, -0.28867513+0.5j], [ 0.+0.j, 1.+0.j, 0.+0.j, -0.28867513-0.5j], [ 0.+0.j, 0.+0.j, 1.+0.j, 0.57735027-0.j ] ] ) python = np.array( [ 0.24235958-0.32852474j, 0.16333098+0.37415192j, -0.40569056-0.04562718j, 0.70267665+0.0790286j ] ) matlab = np.array( [ 0.2235 - 0.3134j, 0.1596 + 0.3502j, -0.4151 + 0.2949j, 0.6636 + 0.0639j ] ) print( 'A @ python =\n', A @ python ) print( '\n\nA @ matlab =\n', A @ matlab ) print( '\n\npython / matlab =\n', python / matlab ) print( '\n\nabs(python) =\n', np.linalg.norm( python ) ) Output: A @ python = [ 6.71328548e-09-6.37871800e-09j 6.71328548e-09+3.62128200e-09j -6.39980441e-09+3.54772201e-09j] A @ matlab = [-1.48162680e-05-4.63408070e-05j -1.48162680e-05-4.63408070e-05j -3.19703608e-02+3.31792682e-01j] python / matlab = [1.06043801+0.01707621j 1.06065285+0.01698805j 0.59761752+0.53448467j 1.06051995+0.01697013j] abs(python) = 1.0000000015891697
Trying to install with pip gives another error: RuntimeError: MATLAB R2022b installation not found. Install to default location, or add <matlabroot>/bin/maca64 to DYLD_LIBRARY_PATH, where <matlabroot> is the root of a MATLAB R2022b installation. even though I have confirmed in matlab that my root is the default /Applications/MATLAB_R2022b.app
When MATLAB is running code (as it does for example in your loop), it does nothing else. UI evens are queued and not handled until the computation (code execution) stops. Instead, let your function terminate. The figure will continue to exist, and will continue to react to UI events. To interact with the COM port at regular time intervals, use timer. Similarly to UI events, the timer will continue running even when MATLAB is idling. Alternatively, if you need to do some long computation and still allow for user interaction, regularly issue a short pause so that UI events can be handled. There is also drawnow, which should allow UI events to be handled, but I have not been very successful with it in the past.
Nested functions don't recognize input
@CrisLuengo, thank you, I will pay attention to the details you have made. I try to build various study materials for my students. This option also helps me carry out individual evaluation instruments.
Ops, you're completely right, would have been too easy..
I don’t know exactly how MATLAB runs Python, but if you can run it using `system` you should also be able to run it in the out-of-process mode. At least, that is what I would expect, I’d expect the two to be more or less the same thing.
I would ask Matlab the question. Matlab has lots of restrictions to maintain license control. It looks like Matlab isn't allowing Excel to run. If it did then you could run excel in a machine that does not have a Microsoft Office License. Why use Microsoft Excel when Matlab has built in Excel Methods.
well, *graphics* only insofar as it's dealing with points and lines and shape intersections perhaps. I modified the tags a little. it certainly is graph theory, and geometry.
Using vpasolve to solve equation in matrix form
I have implemented following equations both with the Matlab own ODE solvers and with a very simple finite difference scheme. The latter works properly, while the ODE code does not produce suitable solutions. What I am doing wrong? These are a set of coupled implicit differential equations. % Define the range of r for the solution r_span = [r2, r_outlet]; % Initial state vector [cm, cu, rho, p] y0 = [cm2, cu2, rho2, p2]; % Define the ODE system syms cm(r) cu(r) rho(r) p(r) eq2 = cm*r*diff(rho) + rho*r*diff(cm)+cm*rho == 0; eq3 = diff(r*cu) == -r^2*cu*cf*rho*sqrt(cu^2+cm^2)/(rho2*cm2*b2*r2); eq4 = diff(p)/rho == -cu*diff(cu)-cm*diff(cm)-(cd*rho*r* (cu^2+cm^2)^1.5)/(rho2*cm2*b2*r2); eq5 = (gamma/(gamma-1))*diff(p/rho) == -cu*diff(cu)-cm*diff(cm); % eqns = [eq1; eq2; eq3; eq4; eq5]; eqns = [ eq2; eq3; eq4; eq5]; [V, S] = odeToVectorField(eqns); odefcn = matlabFunction(V, 'vars', {'r', 'Y'}); opt = odeset('RelTol', 1e-6, 'AbsTol', 1e-8); % Solve the ODE system using ode45 [r_sol, y_sol] = ode15s(@(r, Y) odefcn(r, Y), r_span, y0,opt); Thanks in advance! As said before a comparison with a finite difference (FD) scheme, showed that these code cannot solve the system of equations. Also with FD it was possible to generate physically sound results. For example, conservation of mass is given for FD. In the ODE code this conservation is defined in eq1
I am trying to fill the area between the variable b (size 7301x1) and the minimum value of zaxis (size of zaxis is 1x1376, but I only want to use the minimum value of it) for xaxis (size 7301x1). I attempted the following code: xfill = [xaxis, fliplr(xaxis)]; yfill = [min(zaxis) * ones(size(b)), b]; fill(xfill, yfill, 'r'); The code ran successfully, but it only filled the area for b, creating a triangle shape at the location of b and a separate horizontal line at the minimum zaxis. I would like to fill the area between the horizontal line and the plot of b. How can I achieve this? I also tried using the patch function, but I got the same result. I’m pretty sure I missed something, but I have no idea what. I tried xfill = [xaxis, fliplr(xaxis)]; yfill = [min(zaxis) * ones(size(b)), b]; patch(xfill, yfill, 'r'); I want to fill the area between min(zaxis) and b.
great! consider upvoting the answer if it helped!
Applying reweighting to a 2D Ising Model
Have now fixed this. Thanks to those who replied. I shall try my best to recount all the steps below. Version issues Firstly, I built my own Docker image for Doxygen. I suspect the existing images on Docker Hub (corentinaltepe/doxygen, hrektts/doxygen) would have worked too, but I wanted full visibility for debugging. Here is the Dockerfile that I used to build my Docker image. It runs Doxygen 1.9.8 because that's the latest version available in the Ubuntu default package repository at present. FROM ubuntu:24.04 # Update RUN apt-get update # Install RUN apt-get install -y vim doxygen graphviz # Working directory WORKDIR /doxygen/ I then generated a default Doxyfile from this version of Doxygen and changed the following settings. I think only the first two of these settings really matter, but I have included the remaining four for completeness and because they match the settings in the Doxyfile provided by Fabrice. EXTENSION_MAPPING = .m=C++ FILTER_PATTERNS = *.m=/doxygen/m2cpp.pl EXTRACT_ALL = YES EXTRACT_PRIVATE = YES EXTRACT_STATIC = YES GENERATE_LATEX = NO Having made these changes, I was sure that I was using a relatively recent version of Doxygen. Moreover, I knew that my Doxyfile matched the version of Doxygen. Ie: it didn't contain deprecated settings etc. In hindsite, I don't think any of these version issues were actually causing the problem, but it was good practise to resolve them. EOL issues Secondly, I ran the following Git commands suggested here. git config core.autocrlf false git rm --cached -r . git reset --hard Then I opened m2cpp.pl in VSCode and changed the End of Line (EOL) Sequence in from CRLF to LF. I had tried doing this previously but suspected Git was somehow preventing the change. On this second attempt, having run those three Git commands, the change was successful. I tested this by opening m2cpp.pl from Vim inside of an Ubuntu container and using :e ++ff=unix to show ^M carriage return characters, as suggested here. Sure enough, Vim showed that there were no ^M characters. Shebang issues Thirdly, I changed the first line of m2cpp.pl from #!/usr/bin/perl.exe to #!/usr/bin/perl. Apparently this is another Windows vs Unix thing. That first line tells the OS where to look for the Perl interpreter and Unix doesn't like the .exe suffix. Testing locally Having made these changes, I built and ran my Doxygen container locally by mounting it onto the folder that contained my Dockerfile, Doxyfile, m2cpp.pl and example MATLAB code in need of documentation. docker build doxygen-image . docker run -it --mount type=bind,src=$pwd,dst=/doxygen/ doxygen-image Since I ran the container in interactive mode -it, I was able to manually run commands in it. I ran the following commands inside of the /doxygen/ folder. The first one gives executable permission to m2cpp.pl and the second one runs Doxygen. chmod +x m2cpp.pl doxygen Doxyfile This produced HTML files containing the expected documentation. Very good. Testing in pipeline Finally, I needed to run all of this automatically inside of a BitBucket Pipeline. Here is the bitbucket-pipelines.yml file that I wrote for that. There are no new 'discoveries' here - it just implements the same steps as when I was testing locally. The two export commands are needed for building Docker images inside of a BitBucket Pipeline according to this thread. The command for running docker differs slightly from when I was testing locally. I don't entirely understand the difference, but the output seems to be the same. This automatically generates HTML documentation inside of the Pipeline. At present, I then manually download these files from BitBucket, but I shall configure this to instead send them to the server that will host the documentation. image: docker:27.4.0 pipelines: default: - step: name: Doxygen script: # Give executable permission to Doxygen MATLAB filter - chmod +x m2cpp.pl # Build Docker image - export PATH=/usr/bin:$PATH - export DOCKER_BUILDKIT=1 - docker build -f Dockerfile -t doxygen-image . # Run Docker container, mount pwd, run Doxygen, remove container - docker run --rm -v $(pwd):/doxygen/ doxygen-image /bin/bash -c "doxygen Doxyfile"; artifacts: - html/** services: - docker
Matlab may of fixed a bug or you need a license from Matlab. Does machine you are using have a Microsoft office license? I do not think you can run Excel from Matlab without an office license. You can run excel method using matlab features.
Your code goes wrong on the line zx = x(yz .* circshift(yz,[0 1]) &lt;= 0); yz is a column vector, so circshifting it by 1 in the horizontal direction doesn't do anything at all. Changing the [0 1] into [1 0] makes your code run correctly: s = 1.0e+05 * 0.6986 0.0061 -0.0000 2.1975 To make your code more robust against changes in the input data orientation, you can use circshift(yz,1) instead. Assuming that y is always a vector, this will be correct no matter if it's a column or row vector.
I am writing down a code that first apply Butterworth (low pass filter) to a earthquake time history and then create the one sided fourier amplitude of the filtered motion and multiply it with a transfer function to obtain the modified one sided fourier spectra and in the last step inverse fast fourier transform is applied to obtain acceleration time history of the modified motion. I wrote a complete code, but in the ifft step, it doesn't work, i think it's because of that i am trying gto make ifft from one-sided amplitude spectra in a wrong way. Could you please help me about the last part ? acci=load('Gilroy.txt'); % Butterworth filtresi parametreleri cutoff_freq = 25; % Kesim frekansı (Hz) filter_order = 4; % Filtre derecesi % Butterworth filtresi tasarımı [b, a] = butter(filter_order, cutoff_freq / (200 / 2), 'low'); % Filtreyi ivme kaydına uygulayın acc = filtfilt(b, a, acci); % Earthquake Data Process dt = 0.005; % Zaman adımı g = 9.81; % Yerçekimi ivmesi (m/s^2) t = 0.0:dt:dt*(length(acc)-1); % Hız ve yer değiştirme hesaplama vel = cumsum(acc) * dt * g; dis = cumsum(vel) * dt; % Fourier Transform Ts = dt; Fs = 1 / Ts; ACC = fft(acc, 2^nextpow2(numel(acc))); N = numel(acc); f = (0:(N-1)) / N * Fs; m_ACC = abs(ACC) / N; m_ACC = m_ACC(1:N/2+1); m_ACC(2:end-1) = 2 * m_ACC(2:end-1); % Tek taraflı spektrum f = f(1:N/2+1); % Sadece pozitif frekanslar için eksen % Zemin Parametreleri (Sert kaya üzerinde uniform, sönümsüz zemin) h = 3.05; % Kalınlık (m) Vs = 320; % Vs30 (m/s) k = h / Vs; % Amplifikasyon Fonksiyonu y = 1 ./ abs(cos(k * 2 * pi * f)); % Amplifikasyon Fonksiyonu % Amplifikasyon Fonksiyonu ile çarpma y = y'; N_FAS = y .* m_ACC; % Ters Fourier dönüşümü (tek taraflı spektrumdan dönüşüm) reconstructed_acc = ifft(N_FAS, 'symmetric'); % 'symmetric' seçeneği simetri sağlar reconstructed_acc= reconstructed_acc*length(reconstructed_acc); % Hız ve yer değiştirme hesaplama reconstructed_vel = cumsum(reconstructed_acc) * dt * g; reconstructed_dis = cumsum(reconstructed_vel) * dt; % Zaman eksenini yeniden oluşturma t_reconstructed = 2*(0:length(reconstructed_acc)-1) * dt; % Sonuçları tek bir plot altında toplama (3x3 layout, transposed) figure; subplot(3,3,1), plot(t, acc, '-b'); xlabel('Time (sec)'), ylabel('Original Ground Acceleration (g)'); title('Original Ground Acceleration'); grid on; subplot(3,3,4), plot(t, vel, '-b'); xlabel('Time (sec)'), ylabel('Velocity (m/sec)'); title('Velocity'); grid on; subplot(3,3,7), plot(t, dis, '-b'); xlabel('Time (sec)'), ylabel('Displacement (m)'); title('Displacement'); grid on; subplot(3,3,2), plot(f, m_ACC, '-b'); xlabel('Frequency (Hz)'), ylabel('Original Fourier Amplitude (g-s)'); title('Original Fourier Amplitude (g-s)'); xlim([0 25]); grid on; subplot(3,3,5), plot(f, y, '-b'); xlabel('Frequency (Hz)'), ylabel('Amplification Function'); title('Amplification Function'); xlim([0 25]); grid on; subplot(3,3,8), plot(f, N_FAS, '-b'); xlabel('Frequency (Hz)'), ylabel('Modified Fourier Amplitude (g-s)'); title('Modified Fourier Amplitude (g-s)'); xlim([0 25]); grid on; subplot(3,3,3), plot(t_reconstructed, reconstructed_acc, '-b'); xlabel('Time (sec)'), ylabel('Reconstructed Ground Acceleration (g)'); title('Reconstructed Ground Acceleration'); grid on; subplot(3,3,6), plot(t_reconstructed, reconstructed_vel, '-b'); xlabel('Time (sec)'), ylabel('Reconstructed Velocity (m/sec)'); title('Reconstructed Velocity'); grid on; subplot(3,3,9), plot(t_reconstructed, reconstructed_dis, '-b'); xlabel('Time (sec)'), ylabel('Reconstructed Displacement (m)'); title('Reconstructed Displacement'); grid on; % Plotları düzenleme sgtitle('Earthquake Data Analysis');
With regard to removing the `^M`, I initially tried doing this in VSCode by changing the End of Line Sequence from `CRLF` to `LF`. I was suspicious that this hadn't worked, because Git didn't recognise any changes. I also tried running `dos2unix` on the filter from Powershell, but to no avail. Then I tried opening the file in Vim from inside of the container, and I was able to see and remove all `^M` characters. Surely there's a better way to do this, without me having to edit the file from inside of the container? Sorry for what I expect is a very basic question!
If you have the Image Procressing Toolbox, you can do it easily with im2col (but the code is probably slower than the other options): S = reshape(im2col(M, [N N], 'distinct'), N, N, []);
Any decent code editor will be able to save files with UNIX-style line endings. Even some simple text editors can do this.
MLAPP files provide forward-compatibility, but don't guarantee backward-compatibility. New functionality has been added to App Designer in basically every release since it was introduced, and new functionality will inherently not work in older versions of Matlab. If you want to ensure you can use an MLAPP file in multiple different versions of Matlab, it needs to be compatible with the oldest version that you intend to use. To achieve that, you can either (1) create the app in the old version of Matlab or (2) open it in the version it was created in, and use "save as" to save it for compatibility with the old version. You must make sure the app does not use any functionality not supported in the old version (for example, if it uses uitree then you can't use it with any version prior to 2017b). https://www.mathworks.com/help/matlab/creating_guis/compatibility-between-different-releases-of-app-designer.html https://www.matlabsolutions.com/resources/will-my-app-designer-app-be-compatible-in-previous-and-future-releases-.php As others indicated in comments, MLAPP files are effectively ZIP files with various content inside, similar to Microsoft Word DOCX files. But that doesn't really affect your problem.
I knew this must be possible but couldn't work out the order of operations. I've added this to the benchmarking in my answer since it runs faster than the other options.
Scipy Null Space Innacurate only for Complex Values
This is a graph theory problem and not a graphics problem. You should consider the problem in the form totally abstracted from graphics. The algorithms for finding paths on a graph are well-known. Basically, this is one or another form of the *backtracking* algorithm. Most likely, your graph is a general graph with loops, and it may be directed (when some routes include one-way traffic) or not.
image from MATLAB to illustrate the error I am writing code to solve the well-known equation in matrix form, F = KX to solve a finite element problem. I have resorted the equation to get all the variables on the one side by adding negative eye matrix beside K matrix and initiating another column vector to contain X then F below. I am stuck on how to introduce the unknown variables into MATLAB and finding the proper way to solve this equation so the output can be a matrix of numerical values. Below is the code and associated error: % ____ Solving Section ____ % % Initialize the global stiffness matrix and force vector % K_global is given % X is defined as U_global in this code K_global_2 = sym ([K_global,-1*eye(2*numNodes)]); U_F = sym([U_global;F_global]); % Define symbolic variables for U_global and F_global eqn= K_global_2 * U_F == sym(zeros(2 * numNodes, 1)); % Solve the system using vpasolve solution = vpasolve(eqn, U_F); % Extract the solved displacements and forces U_global_solved = solution.U_global; F_global_solved = solution.F_global; I am getting this error: Error using sym.getEqnsVars&gt;checkVariables (line 98) Second argument must be a vector of symbolic variables. However, U_F is assigned as sym in the workplace as you can see in the attached image I tried to solve equation of F = KX in matrix form. I used solve, vpasolve, linsolve, but couldn't reach any results. I am excepting the out as vector column of numbers or numerical values which is U_F. I do not know what the source of this error is.
Problem with return when calling a python function within matlab
I have the following MATLAB code, which visualizes the difference between DCO-OFDM and m-CAP in terms of coverage area vs. QAM order. The bars represent the coverage area under various configurations, and some of the bar segments are in red and blue, indicating specific effects (e.g., LOS+NLOS). The current legend already describes the configurations (e.g., angles for m-CAP and DCO-OFDM). However, I want to add two additional legend entries specifically for the red and blue bar segments to explain their significance, as shown in the attached image. The goal is to add two additional legends under the existing ones, representing: Red bars: LOS+NLOS Effect on m-CAP. Blue bars: LOS+NLOS Effect on DCO-OFDM. Here's the image that clarifies the desired legend layout: May I get assistance in achieving this? Specifically: How can I add the red and blue legends for these bar colors without disrupting the existing legend? Is there a more efficient way to achieve this result? Thank you in advance for your help! Here’s an example of my MATLAB code for creating the bar chart: close all; clear variables; clc; QAM = [16, 32, 64, 128, 256, 512, 1024]; %% m_CAP modulation % Beamsteering without reflection VEC_Beam_no_reflection_mCAP = [ 117.5491 75.1933 53.5396 38.3105 23.0815 13.5634 6.9007; % Theta = 10 118.2629 76.1452 54.0155 39.0244 23.0815 13.5634 6.9007; % Theta = 30 118.2629 76.3831 54.0155 39.5003 22.8435 13.5634 6.9007; % Theta = 45 118.2629 76.6211 54.2534 39.5003 22.8435 13.5634 6.9007 % Theta = 60 ]; % Beamsteering with reflection VEC_Beam_reflection_mCAP = [ 121.3563 77.0970 54.7293 39.7383 22.8435 13.5634 6.9007; % Theta = 10 141.1065 88.7567 61.6300 42.5937 24.2713 14.5152 7.8525; % Theta = 30 153.7180 95.6573 67.8168 45.6871 26.6508 14.5152 8.8043; % Theta = 45 160.3807 100.6544 69.7204 50.4462 28.7924 16.4188 8.8043 % Theta = 60 ]; %% DCO-OFDM modulation % Beamsteering without reflection VEC_Beam_no_reflection_OFDM = [ 91.3742 59.7264 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10 95.4194 58.2986 34.7412 25.9369 16.4188 10.7079 4.9970; % Theta = 30 89.4706 59.4884 44.4973 24.7472 16.4188 8.8043 4.9970; % Theta = 45 83.5217 69.4825 40.2142 28.7924 16.4188 10.7079 4.9970 % Theta = 60 ]; % Beamsteering with reflection VEC_Beam_reflection_OFDM = [ 94.7055 61.8679 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10 113.9798 69.7204 42.1178 28.7924 16.4188 10.7079 4.9970; % Theta = 30 115.6454 74.9554 55.6811 28.7924 16.4188 9.7561 4.9970; % Theta = 45 114.4557 88.7567 50.6841 34.5033 21.1779 11.6597 4.9970 % Theta = 60 ]; %% Combine Data for Bar Chart angles = [10, 30, 45, 60]; data_no_reflection = [VEC_Beam_no_reflection_mCAP; VEC_Beam_no_reflection_OFDM]; data_with_reflection = [VEC_Beam_reflection_mCAP; VEC_Beam_reflection_OFDM]; % Generate gradient colors for m-CAP (blue) and DCO-OFDM (green) mCAP_blue_gradient = [linspace(0.8, 0.1, 4)', linspace(0.9, 0.2, 4)', linspace(1.0, 0.3, 4)']; % Light to dark blue DCO_green_gradient = [linspace(0.7, 0.1, 4)', linspace(0.9, 0.4, 4)', linspace(0.6, 0.2, 4)']; % Light to dark green % Combine colors custom_colors = [mCAP_blue_gradient; DCO_green_gradient]; f = figure('Position', [100, 100, 800, 600]); % Set "HandleVisibility" to off so these bars don't appear in legend b2 = bar(data_with_reflection', 'grouped','HandleVisibility','off'); for k = 1:length(b2) b2(k).FaceColor = 'flat'; b2(k).CData = repmat([1,0,0], size(b2(k).CData, 1), 1); % [1,0,0] for red bars end % Plot for No Reflection hold on; % To plot 2nd set of bars on top b1 = bar(data_no_reflection', 'grouped'); for k = 1:length(b1) b1(k).FaceColor = 'flat'; b1(k).CData = repmat(custom_colors(k, :), size(b1(k).CData, 1), 1); end % Adjust axis and grid grid on; xticks(1:length(QAM)); xticklabels(string(QAM)); xlabel('QAM Order, M'); ylabel('Coverage Area (m²)'); title({'Coverage Area With Reflection', 'm-CAP and DCO-OFDM'}); % Update the legend legend(["m-CAP \Phi_{1/2}=10°", "m-CAP \Phi_{1/2}=30°", "m-CAP \Phi_{1/2}=45°", "m-CAP \Phi_{1/2}=60°", ... "DCO-OFDM \Phi_{1/2}=10°", "DCO-OFDM \Phi_{1/2}=30°", "DCO-OFDM \Phi_{1/2}=45°", "DCO-OFDM \Phi_{1/2}=60°"], ... 'Location', 'Best');
I have improved the description of the problem to better understand the meaning of "strips". The stripes appear as non-uniformities of noise in the image.
The other bad thing is the data format. If I were you I’d rethink how you store the data. An array has overhead (memory wise). Storing an array by itself inside a cell array doubles the overhead. Also, indexing is relatively expensive in MATLAB. Consider storing all your data in a single array (make it multi-dimensional if appropriate).
I see, thank you. Unfortunately, that doesn't resolve it. From looking at the filtered MATLAB files, it seems that the filter removes all of the function body. Ie: the filtered source code contains only function headers. This is why the callgraphs don't work.
Trying to reshape/ rearrange table variables in MATLAB
I want to identify variables outside of function calls such as result = someFunction(arg1, arg2) + 10 And I used pattern ([a-zA-Z_]\w*)(?!\s*\() In Matlab, the result is {'result'} {'someFunctio'} {'arg1'} {'arg2'} But, I want to get {'result'} {'arg1'} {'arg2'} I'm curious why the function call is also extracted. And also why it is someFunctio.
I'm trying to make a flutter apllication read a 1xN matrix from a .mat file then process this data with a standalone matlab application so when I tried to acheive that the application just loses the connection at some point MATLAB function: function results = singleRVAnalysis(sample, numBins) % SINGLE_RVANALYSIS Analyzes a single random variable sample % % Inputs: % sample - Array of sample data % numBins - Number of bins for histogram (default: 50) % % Outputs: % results - A structure containing PDF, CDF, mean, variance, and third moment if nargin &lt; 2 numBins = 50; end edges = linspace(min(sample), max(sample), numBins + 1); counts = histcounts(sample, edges); binWidth = diff(edges); pdf = counts / (sum(counts) * binWidth(1)); cdf = cumsum(pdf) * binWidth(1); binCenters = edges(1:end-1) + diff(edges) / 2; meanValue = sum(binCenters .* pdf * binWidth(1)); varianceValue = sum(((binCenters - meanValue).^2) .* pdf * binWidth(1)); thirdMomentValue = sum(((binCenters - meanValue).^3) .* pdf * binWidth(1)); results = struct; results.PDF = pdf; results.CDF = cdf; results.Mean = meanValue; results.Variance = varianceValue; results.ThirdMoment = thirdMomentValue; results.Edges = edges; end Flutter Code: import 'dart:ffi'; import 'dart:io'; import 'package:ffi/ffi.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:file_picker/file_picker.dart'; const String dllPath = 'lib\\SingleRVAnalysis\\SingleRVAnalysisLib.dll'; final DynamicLibrary singleRVAnalysisLib = DynamicLibrary.open(dllPath); final class Results extends Struct { external Pointer&lt;Double&gt; pdf; external Pointer&lt;Double&gt; cdf; @Double() external double mean; @Double() external double variance; @Double() external double thirdMoment; external Pointer&lt;Double&gt; edges; @Int32() external int binCount; } typedef SingleRVAnalysisNative = Results Function( Pointer&lt;Double&gt;, Int32, Int32); typedef SingleRVAnalysisDart = Results Function(Pointer&lt;Double&gt;, int, int); final singleRVAnalysis = singleRVAnalysisLib.lookupFunction&lt; SingleRVAnalysisNative, SingleRVAnalysisDart&gt;('mlxSingleRVAnalysis'); enum FileProcessStatus { idle, processing, completed, failed } class FileProcessCubit extends Cubit&lt;Map&lt;String, dynamic&gt;&gt; { FileProcessCubit() : super({'status': FileProcessStatus.idle, 'file': null}); void pickFile() async { try { final result = await FilePicker.platform.pickFiles(); if (result != null &amp;&amp; result.files.single.path != null) { emit({ 'status': FileProcessStatus.processing, 'file': result.files.single, }); await processFile(result.files.single); } else { emit({ 'status': FileProcessStatus.failed, 'error': 'No file selected', }); } } catch (e) { emit({ 'status': FileProcessStatus.failed, 'error': 'File picking error: $e', }); } } Future&lt;void&gt; processFile(PlatformFile file) async { final filePath = file.path; if (filePath == null) { emit({ 'status': FileProcessStatus.failed, 'error': 'No file path available', }); return; } try { final content = await File(filePath).readAsBytes(); if (content.isEmpty) { throw Exception('The file is empty.'); } final List&lt;double&gt; sample = content .toString() .replaceAll(RegExp(r'[^\d\.\-eE, ]'), '') .split(RegExp(r'[,\s]+')) .where((e) =&gt; e.isNotEmpty) .map((e) =&gt; double.tryParse(e) ?? 0.0) .toList(); if (sample.isEmpty) { throw Exception('Sample array is empty.'); } const int numBins = 50; final Pointer&lt;Double&gt; samplePointer = listToPointerDouble(sample); final result = singleRVAnalysis(samplePointer, sample.length, numBins); try { final pdf = result.pdf.asTypedList(numBins).toList(); final cdf = result.cdf.asTypedList(numBins).toList(); final mean = result.mean; final variance = result.variance; final thirdMoment = result.thirdMoment; emit({ 'status': FileProcessStatus.completed, 'mean': mean, 'variance': variance, 'thirdMoment': thirdMoment, 'pdf': pdf, 'cdf': cdf, }); } catch (e) { emit({ 'status': FileProcessStatus.failed, 'error': 'Error during DLL processing: $e', }); } finally { calloc.free(samplePointer); } } catch (e) { emit({ 'status': FileProcessStatus.failed, 'error': 'Processing failed: $e', }); } } void reset() { emit({'status': FileProcessStatus.idle, 'file': null}); } } Pointer&lt;Double&gt; listToPointerDouble(List&lt;double&gt; sample) { final Pointer&lt;Double&gt; pointer = calloc.allocate&lt;Double&gt;(sample.length, alignment: 8); for (int i = 0; i &lt; sample.length; i++) { pointer[i] = sample[i]; } return pointer; } It should allocate the sample pointer then pass it to the function to return the results but It crashes at some point in allocating the samplePointer
The ylabel gets half shown in the graph. Help me solving the problem, such that the ylabel is shown fully. Also, it would be better if the xlabel is moved near to the xtick. The code is written in Matlab. I would request to provide a solution in Matlab itself. Thanks in advance. Below is the Matlab code: clear; % Change default axes fonts. set(0,'DefaultAxesFontName', 'Times New Roman') set(0,'DefaultAxesFontSize', 21) % Change default text fonts. set(0,'DefaultTextFontname', 'Times New Roman') set(0,'DefaultTextFontSize', 21) % Define data x = [100, 200, 300, 400, 500]; data = [ 5.3, 7.3, 4.3, 3.3, 1.3; 4.3, 4.3, 4.3, 5.3, 10.3; 2.3, 7.3, 2.3, 8.3, 2.3; 1.3, 9.3, 8.3, 7.3, 0.3; 9.3, 2.3, 0.3, 2.3, 0.3; 6.3, 7.3, 9.3, 6.3, 7.3; ]; datasetNames = {'A', 'B', 'C', 'D', 'E', 'F'}; % Create a 3D bar chart figure; bar3(data); % Customize the axes set(gca, 'XTickLabel', x, 'YTickLabel', datasetNames, 'FontSize', 21); % Set x-axis labels as number of tasks % Align labels xlh = xlabel('Task Count', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', -30); ylh = ylabel('Method', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', 37); zlh = zlabel('Fitness', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal'); % Set Z-axis limits zlim([0.31, max(data(:))]); % Start Z-axis at 0.0018 % Set view angle for better visualization view(45, 30); % Adjust figure size and layout set(gcf, 'Units', 'normalized', 'Position', [0.2, 0.2, 0.6, 0.6]); % Adjust paper size for saving fig = gcf; fig.PaperUnits = 'centimeters'; fig.PaperPosition = [0 0 14.4 12.4]; fig.PaperSize = [13.4 11.5]; % width &amp; height of page % Save the figure print('FST_D_S2.pdf','-dpdf','-r1200');
You can choose 'UseExcel',false but then you have a different issue with the formula not evaluating unless you manually edit the cell to confirm its contents. It looks like this is primarily an issue in setting the Value or Formula properties of a range, which MATLAB is likely doing under the hood via the COM interface with 'UseExcel',true. For whatever reason, Excel is automatically adding the @ symbol for "implicit intersection" because it's trying to "cleverly" handle the fact that EXACT can return an array output. To get around this you might have to set the .Formula2 data instead. I'll leave the details of the COM interface calls to you, but broadly you've got something like this to get the sheet reference to an open workbook (would work on a closed workbook with different calls): Excel = actxGetRunningServer('Excel.Application'); Workbook = Excel.Workbooks.Item(1); Sheet = Workbook.Sheets.Item(1); Then for some cell c: Sheet.Range('A1:D1').Formula2 = c; You could also write some functions to generate the 'A1:D1' string for you based on the upper-left cell and the size of c,
MATLAB Runtime 2024b TypeInitializationException in COM-registered Windows Forms Control Library
Also, see here for in-process Python execution: https://www.mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html#buuz303 -- and here for out-of-process Python execution: https://www.mathworks.com/help/matlab/matlab_external/reload-python-interpreter.html
`([a-zA-Z]\w*)\>(?!\s*\()` This one works Sorry for unclear question.... The purpose was extract all variable names including left-hand side of equal
How to calculate magnitude for a filter to specific dB level?
@CrisLuengo yes, probably that is the reason. My point was that, we don't need to force all solved null space the same, but checking it meets the definition of "null space" should be sufficient.
I solved the problem by a simple restart of matlab, I was not aware of this apparently simple "issue". So when changing the python code one has to restart matlab to execute the updated python code. Maybe an other solution would be to somehow terminate and reboot the python environment in matlab.
Assuming we have a matrix M of size N^2 x N^2 elements (e.g., 9x9), what's the fastest way to split it into say 3x3 segments (each with 3x3 elements). One way that comes to mind is the following: M = magic(9); N = 3; m = mat2cell(M, N * ones(1, size(M, 1) / N), ... N * ones(1, size(M, 2) / N)); I, however, do not prefer the use of cells. I was curious if there is a way to split the matrix and store the segments in the form of a 3D matrix using a column-major indexing for the segments (e.g., the first segment m{1} becomes m(:, :, 1) and the second segment m{2} becomes m(:, :, 2), and so on).
Here's a minimal example of my problem: innerFunc([2, 4, 5]) % works fine outerFunc(innerFunc, [2, 4, 5]) % doesn't work function out = innerFunc(my_vec) my_vec % not recogniced when called from outerFunc out = -1; end function out = outerFunc(func, my_vec) out = func(my_vec); end This is the output of the code: my_vec = 2 4 5 ans = -1 Not enough input arguments. Error in nested_funcs_bug>innerFunc (line 5) my_vec % not recogniced when called from outerFunc Error in nested_funcs_bug (line 2) outerFunc(innerFunc, [2, 4, 5]) % doesn't work >> I don't know why the eror in line 2? Especially since "innerFunc" usually works and I pass it an input in the outerFunc function.
I have this Matlab code that create a sinusoidal fit from a set of data data = importdata('analisipicco.txt') ; x = data(:,1) ; y = data(:,2) ; yu = max(y); yl = min(y); yr = (yu-yl); % Range of ‘y’ yz = y-yu+(yr/2); zx = x(yz .* circshift(yz,1) <= 0); % Find zero-crossings per = 2*mean(diff(zx)); % Estimate period ym = mean(y); % Estimate offset fit = @(b,x) b(1).*(sin(2*pi*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit fcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function s = fminsearch(fcn, [yr; per; -1; ym]); % Minimise Least-Squares xp = linspace(min(x),max(x)); xlabel("passi motore"); ylabel("intensità (u.a.)"); figure(1) plot(x,y,'o', xp,fit(s,xp), 'r') grid Where the elements of output parameter vector, s ( b in the function ) are: s(1): sine wave amplitude (in units of y) s(2): period (in units of x) s(3): phase (phase is s(2)/(2*s(3)) in units of x) s(4): offset (in units of y) For acknowledge this is my data set: -200 183966 -192 189734 -184 195724 -176 201663 -168 207557 -160 213278 -152 219000 -144 224677 -136 229500 -128 236024 -120 241968 -112 247787 -104 252963 -96 257491 -88 261967 -80 267373 -72 273494 -64 278599 -56 281476 -48 282610 -40 283097 -32 283839 -24 284971 -16 286169 -8 287164 0 287968 8 288561 16 288626 24 288107 32 286967 40 285132 48 282828 56 279847 64 276296 72 272299 80 268080 88 263564 96 258926 104 254052 112 248894 120 243694 128 238177 136 232665 144 227143 152 221959 160 216874 168 211678 176 206540 184 201537 192 196748 200 192091 The program works out fine, but my question is about finding the errors on the parameters and the covariance as well, I could implement the matrix method and finding the covariance matrix but I don't know how to write as a code. I'm new to Matlab so I want to ask if there was some function that calculate the errors as well. Thank you in advance :))
Trying to obtain coefficient matrix of Bspline matrix then obtaining its quasi-diagonal matrix?
The goal is to segment the major paths by turns in a shortest path of a virtual reality map to know how much to score a person's navigation trajectory (blue line in image) based on how far they walked on the shortest path. The problem right now is the algorithm function is plotting the 1st path segment good but the next segment plotted is the same sized bounding box but on the next x,y line segment position of the shortest path (right next to the first x, y line segment - in idealPath variable) How can I fix my current code to detect the next path segment and plot the next bounding segmentation box (in orange)? idealPath which is the shortest path plotted in green in this case is 94666x2 where column 1 is the x position and 2 is the y position to plot as line segments to form the green path in the image. Current code block: function plotSegmentedCheckpoints(trajectory_raw, idealPath, checkpointInfo) % Clear and hold the plot cla; hold on; % Plot ideal path in green plot(idealPath(:,1), idealPath(:,2), 'g.', 'MarkerSize', 5, 'DisplayName', 'Ideal Path'); % Plot trajectory in blue scatter(trajectory_raw(:,1), trajectory_raw(:,2), 15, 'b', 'filled', 'DisplayName', 'Trajectory'); % Get path segments [segmentIndices, numSegments] = findPathSegments(idealPath); % Initialize checkpoint storage checkpoint_bounds = zeros(numSegments, 4); % [x1, x2, y1, y2] reached = false(numSegments, 1); % Constants BOX_WIDTH = 86; % Width of checkpoint boxes % Process each segment for i = 1:numSegments % Get current segment startIdx = segmentIndices(i); endIdx = segmentIndices(i+1); segmentPoints = idealPath(startIdx:endIdx, :); % Calculate segment bounds [bounds, orientation] = calculateSegmentBounds(segmentPoints, BOX_WIDTH); checkpoint_bounds(i,:) = bounds; % Check if trajectory reaches this checkpoint reached(i) = checkCheckpointReached(trajectory_raw, bounds); % Draw checkpoint box drawCheckpointBox(bounds, reached(i), i); % Draw direction arrow to next checkpoint if not last segment if i &lt; numSegments drawDirectionArrow(bounds, idealPath(segmentIndices(i+1),:)); end end % Calculate and display score score = calculateScore(reached, numSegments); % Configure plot configureplot(); % Update title with progress title(sprintf('Checkpoint Progress: (%d/%d)\nScore: %.2f', ... sum(reached), numSegments, score)); % Store checkpoint information checkpointInfo.bounds = checkpoint_bounds; checkpointInfo.reached = reached; checkpointInfo.score = score; end % Function to find path segments based on direction changes function [segmentIndices, numSegments] = findPathSegments(idealPath) % Calculate path directions vectors = diff(idealPath); angles = atan2(vectors(:,2), vectors(:,1)); % Find significant direction changes (&gt; 30 degrees) angleChanges = [true; abs(diff(angles)) &gt; pi/6]; % Combine consecutive changes that are very close MIN_SEGMENT_LENGTH = 50; for i = 2:length(angleChanges)-1 if angleChanges(i) &amp;&amp; angleChanges(i+1) &amp;&amp; ... (i - find(angleChanges(1:i-1), 1, 'last') &lt; MIN_SEGMENT_LENGTH) angleChanges(i) = false; end end % Get indices where direction changes significantly segmentIndices = find(angleChanges); % Ensure first and last points are included if segmentIndices(1) ~= 1 segmentIndices = [1; segmentIndices]; end if segmentIndices(end) ~= size(idealPath,1) segmentIndices = [segmentIndices; size(idealPath,1)]; end % Number of segments numSegments = length(segmentIndices) - 1; end % Function to calculate bounds for a segment function [bounds, orientation] = calculateSegmentBounds(segmentPoints, BOX_WIDTH) % Determine if segment is more vertical or horizontal endpoint_diff = diff(segmentPoints([1 end],:)); is_vertical = abs(endpoint_diff(2)) &gt; abs(endpoint_diff(1)); if is_vertical % Vertical segment x_center = mean(segmentPoints(:,1)); y_range = [min(segmentPoints(:,2)), max(segmentPoints(:,2))]; bounds = [ x_center , % x1 x_center + BOX_WIDTH, % x2 y_range(1), % y1 y_range(2) % y2 ]; orientation = 'vertical'; else % Horizontal segment y_center = mean(segmentPoints(:,2)); x_range = [min(segmentPoints(:,1)), max(segmentPoints(:,1))]; bounds = [ x_range(1), % x1 x_range(2), % x2 y_center , % y1 y_center + BOX_WIDTH % y2 ]; orientation = 'horizontal'; end end % Function to check if trajectory reaches checkpoint function reached = checkCheckpointReached(trajectory, bounds) in_x = trajectory(:,1) &gt;= bounds(1) &amp; trajectory(:,1) &lt;= bounds(2); in_y = trajectory(:,2) &gt;= bounds(3) &amp; trajectory(:,2) &lt;= bounds(4); reached = any(in_x &amp; in_y); end % Function to draw checkpoint box function drawCheckpointBox(bounds, is_reached, checkpoint_number) x = [bounds(1), bounds(2), bounds(2), bounds(1), bounds(1)]; y = [bounds(3), bounds(3), bounds(4), bounds(4), bounds(3)]; if is_reached fill(x(1:4), y(1:4), [0.8 1 0.8], 'FaceAlpha', 0.3, 'EdgeColor', 'k', 'LineWidth', 1); else fill(x(1:4), y(1:4), [1 0.8 0.8], 'FaceAlpha', 0.3, 'EdgeColor', 'k', 'LineWidth', 1); end % Add checkpoint number text(mean([bounds(1), bounds(2)]), mean([bounds(3), bounds(4)]), ... num2str(checkpoint_number), 'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'middle', 'FontSize', 12, ... 'FontWeight', 'bold', 'Color', 'k'); end % Function to draw direction arrow function drawDirectionArrow(current_bounds, next_point) % Calculate arrow start point (center of current box) arrow_start = [ mean([current_bounds(1), current_bounds(2)]), mean([current_bounds(3), current_bounds(4)]) ]; % Calculate direction to next checkpoint dir_vec = next_point - arrow_start; dir_vec = dir_vec / norm(dir_vec) * 50; % Fixed length arrows % Draw arrow quiver(arrow_start(1), arrow_start(2), dir_vec(1), dir_vec(2), 0, ... 'Color', [1 0.5 0], 'LineWidth', 2, 'MaxHeadSize', 0.5); end % Function to calculate score function score = calculateScore(reached, numSegments) weights = linspace(1, 2, numSegments); score = sum(reached .* weights') / sum(weights); end % Function to configure plot function configureplot() grid on; axis equal; set(gca, 'YDir', 'reverse'); xlabel('X Position (cm)'); ylabel('Y Position (cm)'); legend('Location', 'northwest'); xlim([0 600]); ylim([0 600]); end Edit: With Till's suggestion, I was able to implement it and plot the segmented paths onto the figure.
I have a MATLAB application that performs regression using LinearModel.stepwise. I translated the regression process into Python and tried pycaret, OLS, and RLM for regression. However, I noticed differences in the results compared to MATLAB. To ensure consistency, I want to use the MATLAB regression model within my Python application. Locally, I can call MATLAB code from Python using the MATLAB Engine API for Python. However, my long-term goal is to deploy this application on AWS. Since I have no prior experience with AWS, I am trying to understand the best approach. My questions: Do the solutions mentioned in Run MATLAB on AWS and MATLAB in AWS involve running a full MATLAB instance in AWS? Is there an API or service that allows calling specific MATLAB functions and returning results without running a full MATLAB instance in AWS? Any guidance on configuring MATLAB in AWS for this use case would be greatly appreciated.
You can generate a mesh for x-y points in the bounding box of your polygon, then make points outside the polygon equal to NaN using inpolygon, then calculate the surface based on all points, which will be NaN for points outside the polygon. From your example: % Input function and polygon for example f =@(x,y) x.*y; % Polygon is [x, y] points p = [0 0 1 0 2 2 0 1]; % Generate x-y mesh for bounding box of polygon n = 1000; % number of points in each direction x = linspace( min(p(:,1)), max(p(:,1)), n ); % grid points for x y = linspace( min(p(:,2)), max(p(:,2)), n ); % grid points for y [x,y] = meshgrid( x, y ); % all x-y combinations for grid b = inpolygon( x, y, p(:,1), p(:,2) ); % check which points are in the polygon x(~b) = NaN; % make points outside the polygon equal to NaN y(~b) = NaN; % so that f(x,y) is also NaN % Plot the patch of the original polygon and the surface f(x,y) figure(1); clf; hold on; grid on; patch( p(:,1), p(:,2), 'k', 'displayname', 'x-y poly' ); surf( x, y, f(x,y), 'displayname', 'f(x,y) in poly', 'edgecolor', 'flat' ); legend( 'show', 'location', 'north' ); view( 6, 25 ); colormap( 'jet' ); Example output:
Which version of doxygen are you using? Did you have a look at `FILTER_SOURCE_FILES`?
You could split out a table subset for each unique value of Channel, prefix the measurement columns with the corresponding channel name, and then join the table subsets back together on the ID. Here is an example with similar data to in your question, please see the code comments for more details: % Set up example data table ID = [1;1;2;2]; Channel = {'F7';'F8';'F7';'F8'}; Alpha = [9;8;7;6]; Beta = [1;2;3;4]; Gamma = [0.1;0.2;0.3;0.4]; T = table( ID, Channel, Alpha, Beta, Gamma ); % Get the unique channels which need unstacking channels = unique( T.Channel ); for n = 1:numel(channels) % For each channel, get the table subset temp = T( strcmp( T.Channel, channels{n} ), : ); % Remove the redundant Channel column and prefix all non-ID columns % with the channel name for this subset temp.Channel = []; temp.Properties.VariableNames(2:end) = strcat( channels{n}, '_', temp.Properties.VariableNames(2:end) ); % If this is the first iteration then just assign the temp table to the % wide output. Otherwise perform a join on the ID if n == 1 Twide = temp; else Twide = outerjoin( Twide, temp, 'Keys', 'ID', 'MergeKeys', true ); end end Output: Twide = 2×7 table ID F7_Alpha F7_Beta F7_Gamma F8_Alpha F8_Beta F8_Gamma __ ________ _______ ________ ________ _______ ________ 1 9 1 0.1 8 2 0.2 2 7 3 0.3 6 4 0.4
The `^M` can be removed (when using vi) by setting the file to binary mode (`:set bin`) and removing the `^M` characters afterwards or use the command `dos2unix`
The worst part of your code is the line `sum=[sum sumi]`, which creates a new array and copies the data into it. You should never do that inside a loop. Read about preallocation: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html
The second option is what I need, and it works. Thank you very much
Integrating MATLAB Regression into a Python Application on AWS Cloud
Update the content of a MatLab generated executable
What version of setuptools are you using? Usually you can ignore deprecationWarnings, but maybe in your case that's causing the installation to fail.
I have this part of my MATLAB script where im trying to run a python code: %%% MATLAB %%% system(sprintf('python "%s" "%s" "%s"', 'Merge_CT_MRI_targets.py', num2str(OriginalPatients(index_target)), num2str(target_list(index_target)))); disp('test1') This is the python script: ### PYTHON ### import itk import numpy as np import os import time MRI_target = itk.imread("MRI_"+target+"_"+originalPatient+".nii", itk.F) However, it looks like the variables aren't being properly called in the python script: % matlab command window % Traceback (most recent call last): File "Merge_CT_MRI_targets.py", line 23, in <module> MRI_target = itk.imread("MRI_"+target+"_"+originalPatient+".nii", itk.F) ^^^^^^ NameError: name 'target' is not defined Any help is appreciated. I previously tried using pyrunfile but it also brings an error.
So what is wrong with your last approach? You get the Dot files, then you add `\dotfile` commands as you suggest for the manual approach. Is that really too much to do manually? How many functions do you have?
I am trying to translate the following MATLAB code to Python. In MATLAB, the code dynamically updates a single plot for multiple iterations (n = 1:100), and each update displays the interpolation alongside the original function. for n = 1:100 [err, t, f, x, p] = intlag(n); plot(x, sin(x), '-r', x, p, '-b'); % 1./(5*x.*x+1) axis([-1 1 -2 2]) legend('fonction', 'interpolant') title(['t = ', num2str(n)]) drawnow end I attempted to use matplotlib with plt.ion() and plt.pause(), but I couldn't achieve the same smooth dynamic updates. Also, I want to ensure that all updates occur in a single figure. Can someone help me write a Python equivalent for this functionality?
I am trying to train a neural network but I am hitting a snag. I have a simplified version of the problem I am facing: Setup: NN = trainnet(X_data, Y_data, NN, 'crossentropy', options); X_data is size 25455x3 with each of the 3 columns being normalized (mean = 0 and std = 1) Y_data is size 25455x1 of values 1 or 0 (binary classification) (sum(Y_data)= 11541(~45%)) NN is a newly generated dlnetwork from the following code: featureInputLayer(3, "Name", "InputLayer") fullyConnectedLayer(32, "Name", "HiddenLayer1","WeightsInitializer", "he") reluLayer("Name", "ReLU") dropoutLayer(0.2, "Name", "Dropout") fullyConnectedLayer(1, "Name", "OutputLayer","WeightsInitializer", "glorot") sigmoidLayer("Name", "SigmoidOutput") ]; NN = dlnetwork(NN); options: options = trainingOptions("adam", ... LearnRateSchedule = "piecewise", ... LearnRateDropFactor = 0.2, ... LearnRateDropPeriod = 5, ... MaxEpochs = 1, ... MiniBatchSize = 128, ... ExecutionEnvironment = "cpu", ... Plots = "none"); Problem: When I run the single line NN = trainnet(X_data, Y_data, NN, 'crossentropy', options);, the model runs 194 iterations with the final trainingloss being 0.044545, however the tested accuracy of the model is only ~45% on similar test data, but more concerning is predictions generated with similar data are very skewed towards one. In fact, the lowest prediction is 0.6876 and the mean is 0.9030. This is a massive jump and one that does not make sense to me. I would expect the model's predictions to stay approximately normal about 0.5 (not considering for the moment any learning) or maybe a bit less to match the slighly lower amount of labels of 1. Why is this happening and how can I fix it? Note: What I am really doing is running a loop that runs the line of code I talked about above. The problem I have descibed is just the first iteration of the loop; as it continues, the skew becomes more extreme until all predictions are just 1.00000. The data is different each time through the loop, however it is very similar and there are trends in it that should be learnable (found from other types of regression modeling).
You can create two fake bar plots with those colors, using NaN values so that the bars are not shown in the graph but they appear in the legend. To do this, replace your last line by bar(NaN, NaN, 'r') % fake red bar bar(NaN, NaN, 'b') % fake blue bar % Update the legend legend(["m-CAP \Phi_{1/2}=10°", "m-CAP \Phi_{1/2}=30°", ... "m-CAP \Phi_{1/2}=45°", "m-CAP \Phi_{1/2}=60°", ... "DCO-OFDM \Phi_{1/2}=10°", "DCO-OFDM \Phi_{1/2}=30°", ... "DCO-OFDM \Phi_{1/2}=45°", "DCO-OFDM \Phi_{1/2}=60°", ... "Red, \Phi_{1/2}=60°", "Blue, \Phi_{1/2}=60°"], ... % text for red and blue 'Location', 'Best');
You need to explicitly account for these parameters within your custom loss function. Below an example, but adjust accordingly: function loss = modelLoss(Y, T, classNames, classWeights) % normalized to 1 classWeights = classWeights / sum(classWeights); mask = ~isnan(T); T(isnan(T)) = 0; numClasses = numel(classNames); T_onehot = zeros([size(T, 1), size(T, 2), numClasses, size(T, 4)], 'like', Y); for i = 1:numClasses T_onehot(:, :, i, :) = (T == i); end % class-wise weighted cross-entropy weightedLoss = 0; for c = 1:numClasses classMask = mask &amp; (T == c); weightedLoss = weightedLoss + classWeights(c) * crossentropy(Y(:, :, c, :), T_onehot(:, :, c, :), Mask=classMask); end % Normalize by # of valid pixels numValidPixels = sum(mask(:)); loss = weightedLoss / max(numValidPixels, 1); end % Define weights classNames = [...]; classWeights = [...]; % Example weights customLoss = @(Y, T) modelLoss(Y, T, classNames, classWeights); netTrained = trainnet(images, net, customLoss, options);
Thanks for the solution! Using Formula2 worked a charm.
I'm trying to find normal depth and critical depth using flow parameters with app designer. First, I defined the variables globally and set the parameters equal to their abbreviations. Then, I defined the all variables and defined function CALCULATEButtonPushed(app, event) for finding normal depth and critical depth. When I enter the parameters and run the "Calculate" button, I want to see the normal depth and critical depth in the box. When I first ran the code by entering the parameters (BB, ZZ, S0, N, QQ), it was working fine, but today, when I run the "Calculate" button, the system is stuck with a bug. If there is something I missed in the code, I would be glad if you could help me. appdesigner image classdef example < matlab.apps.AppBase % Properties that correspond to app components properties (Access = public) UIFigure matlab.ui.Figure TabGroup matlab.ui.container.TabGroup SteadyTab matlab.ui.container.Tab CALCULATEButton matlab.ui.control.Button INPUTPARAMETERSLabel matlab.ui.control.Label CRITICALDEPTHEditField matlab.ui.control.NumericEditField CRITICALDEPTHEditFieldLabel matlab.ui.control.Label NORMALDEPTHEditField matlab.ui.control.NumericEditField NORMALDEPTHEditFieldLabel matlab.ui.control.Label STEADYSTATEDISCHARGEEditField matlab.ui.control.NumericEditField STEADYSTATEDISCHARGEEditFieldLabel matlab.ui.control.Label MANNINGsVALUEEditField matlab.ui.control.NumericEditField MANNINGsVALUEEditFieldLabel matlab.ui.control.Label BEDSLOPEEditField matlab.ui.control.NumericEditField BEDSLOPEEditFieldLabel matlab.ui.control.Label SIDEINCLINATIONEditField matlab.ui.control.NumericEditField SIDEINCLINATIONEditFieldLabel matlab.ui.control.Label BOTTOMWIDTHmEditField matlab.ui.control.NumericEditField BOTTOMWIDTHmEditFieldLabel matlab.ui.control.Label Unsteady2DTab matlab.ui.container.Tab end % Callbacks that handle component events methods (Access = private) % Value changed function: BOTTOMWIDTHmEditField function BOTTOMWIDTHmEditFieldValueChanged(app, event) global BB BB = app.BOTTOMWIDTHmEditField.Value; end % Value changed function: SIDEINCLINATIONEditField function SIDEINCLINATIONEditFieldValueChanged(app, event) global ZZ ZZ = app.SIDEINCLINATIONEditField.Value; end % Value changed function: BEDSLOPEEditField function BEDSLOPEEditFieldValueChanged(app, event) global S0 S0 = app.BEDSLOPEEditField.Value; end % Value changed function: MANNINGsVALUEEditField function MANNINGsVALUEEditFieldValueChanged(app, event) global N N = app.MANNINGsVALUEEditField.Value; end % Value changed function: STEADYSTATEDISCHARGEEditField function STEADYSTATEDISCHARGEEditFieldValueChanged(app, event) global QQ QQ = app.STEADYSTATEDISCHARGEEditField.Value; end % Button pushed function: CALCULATEButton function CALCULATEButtonPushed(app, event) global YNN BB ZZ QQ S0 N YC % function A = AREA(B, YY, Z) % A = (B + Z * YY) * YY; % end AREA = @(B, YY, Z) (B + Z*YY) * YY; PERI = @(B, YY, Z) B + 2*YY*(1 + Z^2)^0.5; % Calculate normal depth YNN = 0.01; while true ETOTAL = (QQ*N)/S0^0.5; ECHECK = AREA(BB, YNN, ZZ)^(5/3) / PERI(BB, YNN, ZZ)^(2/3); if ETOTAL < ECHECK break; end YNN = YNN + 0.01; end % Calculate critical depth W = QQ / (3.132 * BB^2.5); if ZZ == 0 YCOB = W^0.672717 * 1.022785; elseif ZZ == 0.5 YCOB = W^0.602684 * 0.748173; elseif ZZ == 1 YCOB = W^0.574105 * 0.657397; elseif ZZ == 1.5 YCOB = W^0.564345 * 0.625201; elseif ZZ == 2 YCOB = W^0.552851 * 0.584043; elseif ZZ == 2.5 YCOB = W^0.545379 * 0.552333; elseif ZZ == 3 YCOB = W^0.537298 * 0.523298; elseif ZZ == 4 YCOB = W^0.524667 * 0.487638; end YC = YCOB * BB; app.NORMALDEPTHEditField.Value = YNN; app.CRITICALDEPTHEditField.Value = YC; end end % Component initialization methods (Access = private) % Create UIFigure and components function createComponents(app) % Create UIFigure and hide until all components are created app.UIFigure = uifigure('Visible', 'off'); app.UIFigure.Position = [100 100 1016 588]; app.UIFigure.Name = 'MATLAB App'; % Create TabGroup app.TabGroup = uitabgroup(app.UIFigure); app.TabGroup.Position = [3 79 1014 492]; % Create SteadyTab app.SteadyTab = uitab(app.TabGroup); app.SteadyTab.Title = 'Steady'; % Create BOTTOMWIDTHmEditFieldLabel app.BOTTOMWIDTHmEditFieldLabel = uilabel(app.SteadyTab); app.BOTTOMWIDTHmEditFieldLabel.HorizontalAlignment = 'right'; app.BOTTOMWIDTHmEditFieldLabel.Position = [21 377 120 22]; app.BOTTOMWIDTHmEditFieldLabel.Text = 'BOTTOM WIDTH (m)'; % Create BOTTOMWIDTHmEditField app.BOTTOMWIDTHmEditField = uieditfield(app.SteadyTab, 'numeric'); app.BOTTOMWIDTHmEditField.ValueChangedFcn = createCallbackFcn(app, @BOTTOMWIDTHmEditFieldValueChanged, true); app.BOTTOMWIDTHmEditField.Position = [156 377 40 22]; % Create SIDEINCLINATIONEditFieldLabel app.SIDEINCLINATIONEditFieldLabel = uilabel(app.SteadyTab); app.SIDEINCLINATIONEditFieldLabel.HorizontalAlignment = 'right'; app.SIDEINCLINATIONEditFieldLabel.Position = [30 340 111 22]; app.SIDEINCLINATIONEditFieldLabel.Text = 'SIDE INCLINATION'; % Create SIDEINCLINATIONEditField app.SIDEINCLINATIONEditField = uieditfield(app.SteadyTab, 'numeric'); app.SIDEINCLINATIONEditField.ValueChangedFcn = createCallbackFcn(app, @SIDEINCLINATIONEditFieldValueChanged, true); app.SIDEINCLINATIONEditField.Position = [156 340 40 22]; % Create BEDSLOPEEditFieldLabel app.BEDSLOPEEditFieldLabel = uilabel(app.SteadyTab); app.BEDSLOPEEditFieldLabel.HorizontalAlignment = 'right'; app.BEDSLOPEEditFieldLabel.Position = [68 303 73 22]; app.BEDSLOPEEditFieldLabel.Text = 'BED SLOPE'; % Create BEDSLOPEEditField app.BEDSLOPEEditField = uieditfield(app.SteadyTab, 'numeric'); app.BEDSLOPEEditField.ValueChangedFcn = createCallbackFcn(app, @BEDSLOPEEditFieldValueChanged, true); app.BEDSLOPEEditField.Position = [156 303 40 22]; % Create MANNINGsVALUEEditFieldLabel app.MANNINGsVALUEEditFieldLabel = uilabel(app.SteadyTab); app.MANNINGsVALUEEditFieldLabel.HorizontalAlignment = 'right'; app.MANNINGsVALUEEditFieldLabel.Position = [29 266 112 22]; app.MANNINGsVALUEEditFieldLabel.Text = 'MANNING''s VALUE'; % Create MANNINGsVALUEEditField app.MANNINGsVALUEEditField = uieditfield(app.SteadyTab, 'numeric'); app.MANNINGsVALUEEditField.ValueChangedFcn = createCallbackFcn(app, @MANNINGsVALUEEditFieldValueChanged, true); app.MANNINGsVALUEEditField.Position = [156 266 40 22]; % Create STEADYSTATEDISCHARGEEditFieldLabel app.STEADYSTATEDISCHARGEEditFieldLabel = uilabel(app.SteadyTab); app.STEADYSTATEDISCHARGEEditFieldLabel.HorizontalAlignment = 'right'; app.STEADYSTATEDISCHARGEEditFieldLabel.Position = [253 372 168 22]; app.STEADYSTATEDISCHARGEEditFieldLabel.Text = 'STEADY STATE DISCHARGE'; % Create STEADYSTATEDISCHARGEEditField app.STEADYSTATEDISCHARGEEditField = uieditfield(app.SteadyTab, 'numeric'); app.STEADYSTATEDISCHARGEEditField.ValueChangedFcn = createCallbackFcn(app, @STEADYSTATEDISCHARGEEditFieldValueChanged, true); app.STEADYSTATEDISCHARGEEditField.Position = [436 372 40 22]; % Create NORMALDEPTHEditFieldLabel app.NORMALDEPTHEditFieldLabel = uilabel(app.SteadyTab); app.NORMALDEPTHEditFieldLabel.HorizontalAlignment = 'right'; app.NORMALDEPTHEditFieldLabel.Position = [319 295 100 22]; app.NORMALDEPTHEditFieldLabel.Text = 'NORMAL DEPTH'; % Create NORMALDEPTHEditField app.NORMALDEPTHEditField = uieditfield(app.SteadyTab, 'numeric'); app.NORMALDEPTHEditField.Position = [434 295 40 22]; % Create CRITICALDEPTHEditFieldLabel app.CRITICALDEPTHEditFieldLabel = uilabel(app.SteadyTab); app.CRITICALDEPTHEditFieldLabel.HorizontalAlignment = 'right'; app.CRITICALDEPTHEditFieldLabel.Position = [316 258 103 22]; app.CRITICALDEPTHEditFieldLabel.Text = 'CRITICAL DEPTH'; % Create CRITICALDEPTHEditField app.CRITICALDEPTHEditField = uieditfield(app.SteadyTab, 'numeric'); app.CRITICALDEPTHEditField.Position = [434 258 40 22]; % Create INPUTPARAMETERSLabel app.INPUTPARAMETERSLabel = uilabel(app.SteadyTab); app.INPUTPARAMETERSLabel.FontWeight = 'bold'; app.INPUTPARAMETERSLabel.Position = [44 421 127 22]; app.INPUTPARAMETERSLabel.Text = 'INPUT PARAMETERS'; % Create CALCULATEButton app.CALCULATEButton = uibutton(app.SteadyTab, 'push'); app.CALCULATEButton.ButtonPushedFcn = createCallbackFcn(app, @CALCULATEButtonPushed, true); app.CALCULATEButton.Position = [360 224 100 23]; app.CALCULATEButton.Text = 'CALCULATE'; % Create Unsteady2DTab app.Unsteady2DTab = uitab(app.TabGroup); app.Unsteady2DTab.Title = 'Unsteady 2D'; % Show the figure after all components are created app.UIFigure.Visible = 'on'; end end % App creation and deletion methods (Access = public) % Construct app function app = example % Create UIFigure and components createComponents(app) % Register the app with App Designer registerApp(app, app.UIFigure) if nargout == 0 clear app end end % Code that executes before app deletion function delete(app) % Delete UIFigure when app is deleted delete(app.UIFigure) end end end
I'm relatively new to SPM and related tools, and run into some issues running CAT12 segmentation in batches. Individual subjects through the GUI works fine, but when we submit a script to process several subjects, several issues arise: issue 1: MATLAB:sizeDimensionsMustMatch Arrays have incompatible sizes for this operation. Which arrays is it referring to here? How can I check and correct? issue 2: MATLAB:UndefinedFunction Unrecognized function or variable "VI". Which variable are they referring to? issue 3: Error reading header file For some of these issues, some output is still produced, but we struggle to distinguish when a subject has run succesfully. For issue 3, the complete output is not produced. We run a bash submission script on a slurm cluster that calls a matlab script for the CAT12 segmentation: Bash script: #!/bin/bash #SBATCH --job-name=segmentations_ahead #SBATCH --mem=4G #SBATCH --partition=luna-cpu-short #SBATCH --qos=anw-cpu #SBATCH --cpus-per-task=4 #SBATCH --time=00-03:00:00 #SBATCH --nice=2000 #SBATCH --array=1-3%3 #SBATCH --output=slurm-%A.%a.out # Load Matlab module module load matlab/R2021b export MATLABPATH=path/to/cat12 inputdir=path/to/input cd ${inputdir} ls -d sub-*/ | sed 's:/.*::' > subjects.txt subjects=${inputdir}/subjects.txt subj=$(sed -n "${SLURM_ARRAY_TASK_ID}p" ${subjects}) # random delay duration=$((RANDOM % 20 + 2)) echo -e "${YELLOW}INITIALIZING...(wait a sec)${NC}" echo sleep ${duration} matlab -nodisplay -batch "AHEAD_segmentation $inputdir $subj" Matlab script: function AHEAD_segmentation(inputdir,subj) % Define paths addpath('path/to/spm12'); % Get a list of all subject directories %subjects = dir(fullfile(input_dir, 'sub-*')); % Loop over each subject %for i = 1:length(subjects) % Define the subject's anat directory within ses-1 subj_dir = fullfile(inputdir, subj, 'ses-1', 'anat'); % t1_image_gz = fullfile(subj_dir, [subj '_ses-1_acq-wb_mod-t1w_orient-std_brain.nii.gz']); t1_image = fullfile(subj_dir, [subj '_ses-1_acq-wb_mod-t1w_orient-std_brain.nii']); % Show file path disp(['Checking: ', t1_image]); % Check if file exists if exist(t1_image, 'file') ~= 2 fprintf('Warning: File %s not found!\n', t1_image); error('no T1 file'); % Skip to next subject if T1 is missing end % Check if the gzipped T1 image exists if ~isfile(t1_image) fprintf('T1 image not found for subject %s\n', subj); end % Print status fprintf('Processing subject %s\n', subj); % Set up CAT12 batch job for segmentation matlabbatch{1}.spm.tools.cat.estwrite.data = {t1_image}; matlabbatch{1}.spm.tools.cat.estwrite.nproc = 1; %matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = {fullfile(spm('path/to/spm12'), 'tpm', 'TPM.nii')}; % Path to SPM's TPM file spm_dir = spm('dir'); % Path to TPM file tpm_file = fullfile(spm_dir, 'tpm', 'TPM.nii'); % Check if the file exists if ~exist(tpm_file, 'file') error('TPM file not found: %s', tpm_file); end matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = {tpm_file}; % select modality for SPM matlabbatch{1}.spm.tools.cat.estwrite.opts.modality = 'T1'; % Output options for volume-based analysis matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; % Disable surface-based outputs matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 1; % Output native gray matter volume matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 1; % Output native white matter volume matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 1; % Output native CSF volume matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 0; % Output normalized gray matter volume (in MNI space) matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 0; % Output normalized white matter volume (in MNI space) matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; % Output normalized CSF volume (in MNI space) matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 0; % Output modulated gray matter volume (useful for VBM) matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 0; % Output modulated white matter volume matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1]; % Save forward and inverse deformation fields % Run the CAT12 segmentation % spm('defaults', 'FMRI'); % spm_jobman('initcfg'); spm_jobman('run', matlabbatch); Any thoughts on how to tackle any of these three issues (or links to similar issues/documentation/FAQ) would be greatly appreciated!
I want to Publish on a web page a LaTeX expression built with the Matlab latex function. I am using the native Publish button. I can Publish this expression, only if I write it directly: % $P(s) = s^3+6\,s^2+11\,s+6$ Is there any way to Publish the same expression, but from a LaTeX variable? Evenmore, how to Publish the LaTeX variable within a nested HTML code? I understand it could be not possible, since Publishing is made from a comment line, but, could I built a comment expression from a string? This is the code I wrote: %% Publish LaTeX in HTML % How to publish a variable LaTeX %% Polynomial % Define p(x) polynomial, and simbolic and LaTeX strings syms s P = [1,6,11,6] % Defining P(s) polynomial (numeric treatment) symP = poly2sym(P,s) % symbolic string pretty(symP) % display pretty form ltxP = latex(symP) % LaTeX string %% Publish in HTML % Publishing P(s) in HTML is posible with the direct description of the % polynomial: % % $P(s) = s^3+6\,s^2+11\,s+6$ % % But, how to publish the same polynomial P(s) from the LaTeX variable? % % $P(s) = ltxP$ % % % % Evenmore, how to publish the LaTeX variable within a nested HTML code? is % this possible? % $P(s)=ltxP$ % \(P(s)=ltxP\) % $$P(s)=ltxP$$ %
Well, did you look at the documentation? https://www.mathworks.com/help/stats/classificationdiscriminant.html#bs1qffl-1_sep_shared-Coeffs : "The equation of the boundary between class `i` and class `j` is `Const + Linear * x + x' * Quadratic * x = 0`, where x is a column vector of length p." That doesn't look anywhere near what you're doing.
Unrelated: don’t use `clear all`. `clear`, by itself, clears all variables from the workspace. `clear all` also unloads all functions you’ve used previously, which only serves to slow MATLAB down the next time you call those functions. https://www.mathworks.com/help/matlab/ref/clear.html — Also, `clear variables` is the same as `clear`.
I have just spotted the `^M` carriage return character in my final code snippet. So this suggests that the `m2cpp.pl` filter has a Windows-style line ending in the opening line `#!/usr/bin/perl.exe`, which is confusing the Unix-based Docker container. Not sure how to remove this.
While migrating to Python from Matlab, I get different result for StateSystem transform. In Matlab,there is a 2 in 2 out system: tf1 = -4 -------------------------------- 1e06 s^3 + 30000 s^2 + 300 s + 1 Numerator: {[0 0 0 -4]} Denominator: {[1000000 30000 300 1]} tf2 = 0 Numerator: {[0 0 0]} Denominator: {[5600 150 1]} tf3 = 0.75 -------------------- 5600 s^2 + 150 s + 1 Numerator: {[0 0 0.7500]} Denominator: {[5600 150 1]} MatlabCode: sys=[tf1,tf2;tf3,0]; sys_ss=ss(sys); the output is: sys_ss = A = x1 x2 x3 x4 x5 x1 -0.03 -0.0192 -0.008192 0 0 x2 0.01562 0 0 0 0 x3 0 0.007812 0 0 0 x4 0 0 0 -0.02679 -0.01143 x5 0 0 0 0.01562 0 B = u1 u2 x1 0.25 0 x2 0 0 x3 0 0 x4 0.125 0 x5 0 0 C = x1 x2 x3 x4 x5 y1 0 0 -0.1311 0 0 y2 0 0 0 0 0.06857 D = u1 u2 y1 0 0 y2 0 0 In Python，I use control.ss: import control num11 = [0,0,0,-4] num12 = [0,0,0] num21 = [0,0,0.7500] num22 = [0] row1 = [num11, num12] row2 = [num21, num22] numerator = [row1, row2] denominator = [ [[1000000, 30000, 300,1], [5600,150,1]], [[5600,150,1], [1]] ] G = control.tf(numerator, denominator) control.ss(G ) Then I got StateSpace: enter image description here What am I missing here? How can I fix to get the exact same result?
how would you add variables when using system ? I have tried this: system(sprintf('python "%s" "%s" "%s"', 'Merge_CT_MRI_targets.py', num2str(OriginalPatients(index_target)), num2str(target_list(index_target)))); but it doesn't seem to load the variables correctly
@Diusha Maybe turn off the menus? See the `MenuBar` option: https://www.mathworks.com/help/matlab/ref/matlab.ui.figure-properties.html#d126e527403
@CrisLuengo I'm not sure how to explain without sounding condescending and I believe you are causing an xy problem, please re-read the question carefully. In the example they have 2 variables, x1 and x2. I want to use only 1 variable not 2... so just x1, with y1 being the control variable, similar to fig 1 in my code. You state "You need to use both co-ords.. if you want to draw anything other than a vertical line" I'm afraid y = x^2 begs to differ. I am ignoring the linear because I want quadratic discriminant analysis. You may be correct that this is wrong... but what is right?
After using mat2cell, you can concatenate the 2D matrices into a 3D matrix with m = cat( 3, m{:} ); This will satisfy "m{1} becomes m(:, :, 1)" etc. A different option would be to take each strip of N rows and reshape them directly into an NxNxN matrix of segments, assigning them as the next chunk of the NxNx(N^2) output matrix m = NaN(N,N,N^2); for ii = 1:N:N^2 m(:,:,ii:(ii+N-1)) = reshape( M(ii:(ii+N-1),:), N, N, N ); end Note that the segments in these two options are in a different order (the first goes down then across for sub-matrices, the latter goes across then down). If you wanted this loop and reshape version to match the mat2cell version exactly you would need to do a couple of transpose operations with the reshape to get the ordering right m = NaN(N,N,N^2); for ii = 1:N:N^2 m(:,:,ii:(ii+N-1)) = pagetranspose( reshape( M(:,ii:(ii+N-1)).', N, N, N ) ); end There is only a very small performance penalty for doing the additional transpose operations. Update with benchmarking I was curious which of the options above would be faster, so wrote the benchmark at the bottom here (wrapper for the code suggested in the answer above). Here is the resulting plot, so looping and assigning directly into a numeric matrix is faster than going via a cell regardless of N: I've also included chtz's answer which just uses reshape and permute, and gives the same result as the mat2cell and pagetranspose options above much faster, and with less dependency on N, so I would recommend their solution. I've also included Luis' answer for completeness. Benchmarking code: Nmax = 17; t = zeros(Nmax,2); for N = 2:Nmax M = (1:N^2) + 0.1*(1:N^2).'; t(N,1) = timeit( @() opt1(N,M) ); t(N,2) = timeit( @() opt2(N,M) ); t(N,3) = timeit( @() opt3(N,M) ); t(N,4) = timeit( @() opt4(N,M) ); t(N,5) = timeit( @() opt5(N,M) ); end figure(1); clf; hold on; grid on; legend( 'show', 'fontsize', 14 ); plot( 1:Nmax, t(:,1), 'displayname', 'mat2cell and cat', 'linewidth', 2 ); plot( 1:Nmax, t(:,2), 'displayname', 'loop and reshape', 'linewidth', 2 ); plot( 1:Nmax, t(:,3), 'displayname', 'loop and reshape (2)', 'linewidth', 2 ); plot( 1:Nmax, t(:,4), 'displayname', 'reshape and permute', 'linewidth', 2 ); plot( 1:Nmax, t(:,5), 'displayname', 'im2col', 'linewidth', 2 ); ylabel( 'Time (sec)' ); xlabel( 'N' ); m = opt3( N, M ); function m = opt1( N, M ) m = mat2cell(M, N * ones(1, size(M, 1) / N), ... N * ones(1, size(M, 2) / N)); m = cat( 3, m{:} ); end function m = opt2( N, M ) m = NaN(N,N,N^2); for ii = 1:N:N^2 m(:,:,ii:(ii+N-1)) = reshape( M(ii:(ii+N-1),:), N, N, N ); end end function m = opt3( N, M ) m = NaN(N,N,N^2); for ii = 1:N:N^2 m(:,:,ii:(ii+N-1)) = pagetranspose( reshape( M(:,ii:(ii+N-1)).', N, N, N ) ); end end function m = opt4( N, M ) m = reshape(permute(reshape(M, N,N,N,N), [1,3, 2,4]), N,N, N*N); end function m = opt5( N, M ) m = reshape(im2col(M, [N N], 'distinct'), N, N, []); end
I’m facing a blocking issue with MATLAB Runtime in a COM-registered Windows Forms Control Library inside an external application. The issue arises when I instantiate a MWArray (or anything from the MATLAB Runtime), throwing a TypeInitializationException. Exception: System.TypeInitializationException HResult=0x80131534 Message=The type initializer for 'MathWorks.MATLAB.NET.Arrays.MWNumericArray' threw an exception. Source=MWArray StackTrace: at MathWorks.MATLAB.NET.Arrays.MWNumericArray..ctor(Double scalar) at TestWindowsFormsControlLibrary.UserControl1..ctor() in ...\SandboxSolution\TestWindowsFormsControlLibrary\UserControl1.cs:line 32 This exception was originally thrown at this call stack: [External Code] Inner Exception 1: TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception. Inner Exception 2: TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception. Inner Exception 3: Exception: Trouble initializing libraries required by .NET Assembly. In other words: The issue occurs only when the control library is COM-registered and loaded in an external application (e.g., Excel). Without the COM registration, the same control works perfectly in a standalone Windows Forms App or WPF application. Error Trigger Code The exception occurs when initializing MWArray like so: MWArray test = new MWNumericArray(0); If I remove this line, the COM application runs fine (no interaction with MATLAB Runtime). If I run the same control in a standard Windows Forms App or WPF App, it loads the MATLAB Runtime without issues. Steps to reproduce: Create a Windows Forms Control Library. Set up as described in MATLAB documentation. Use the MATLAB Runtime library (e.g., initialize a MWArray). Build and test it within a Windows Forms App or WPF App — it works fine. Register the control as a COM component and use it in an external application (e.g., Excel). The TypeInitializationException is thrown. Environment MATLAB Runtime version: 2024b 64-bit .NET Framework: 4.8.1 64-bit COM architecture: Only 64-bit (AnyCPU is removed) Expected result: I expect the MATLAB Library works in the COM-registered control as the Windows Forms Application. Additional notes: I have only one MATLAB Runtime installed. I have it added in the PATH and it is the only entry.
The image shows “τ”, but your text says “2”. Is that intentional?
I am running certain part of a python code in MATLAB, that brings problems. I have python 3.11.9, and MATLAB 2023b. However, the same part of the code runs perfectly in vscode. It is related to the itk-elastix python library (which im running the 0.21.0 version) The python code: import itk import numpy as np import matplotlib.pyplot as plt import os from scipy.ndimage import rotate import scipy.ndimage as ndi import ipywidgets as widgets from ipywidgets import interact, IntSlider import time ## Merge CT from patient XXXX and targets from YYYY os.chdir('C:/Users/Admin/...') print("Test0") nr = '0000' MRh = itk.imread("NIIFT/MRI_"+nr+".nii", itk.F) CTh = itk.imread("NIIFT/CT_"+nr+".nii", itk.F) print("Test1") fixed_image = CTh resize_factor = 1 moving_image = MRh print("Test2") parameter_object = itk.ParameterObject.New() parameter_object.ReadParameterFile("ParametersRigid.txt") print("Test3") This is the part of the code that brings me problems: result_image, rigid_parameters = itk.elastix_registration_method( fixed_image, moving_image, parameter_object=parameter_object, log_to_console=False) print(parameter_object) print("Test4") itk.imwrite(result_image, "NIIFT/MRI_Corr_"+nr+".nii") print("Test5") I run it in MATLAB, with the following code: pyrunfile("Merger_CT_X_TARGET_Y.py"); And it brings the error: >> MergeFromMatlab Test0 Test1 Test2 Test3 (...some prints here) Error using py.exec Python process terminated unexpectedly. To restart the Python interpreter, first call "terminate(pyenv)" and then call a Python function. Error in MergeFromMatlab (line 3) pyrunfile("Merger_CT_X_TARGET_Y.py"); Whenever this error happens, I have to restart MATLAB. The part of the code before 'Test 4' works correctly. I would appreciate some help
Welcome to Stack Overflow. What's printed out when your run the script? Given that you did include print() statements, some sort of print sequences should appear. I'm not familiar with Matlab so dunno what happens with stdout output.
I was looking to find a way to get essential matrix in opencv. I found these two links that was for the function: https://docs.opencv.org/3.4/d9/d0c/group__calib3d.html#ga0b166d41926a7793ab1c351dbaa9ffd4 and https://amroamroamro.github.io/mexopencv/matlab/cv.findEssentialMat.html In the second link you can see on top this "cv.findEssentialMat - MATLAB File Help ". I was confused. Is it using Matlab somewhow? Because I would like not to do it then. Thanks!
What could be the cause of my SPM CAT12 preprocessing errors?
This will not preserve the same order as in the OP's described output, for example the first 3x3 "segment" would just be a reshaped version of the first column, rather than the upper-right 3x3 submatrix
'variables' passed on the commandline to python need to be read into python variables , use the sys module. variable1=sys.argv[1] , variableN= sys.argv[n] etc
I have another question. If I wanted to do 1D quadratic discriminant (i.e. find the boundary with only the x axis as the variable, y axis as a control), how would I modify this answer? I guess you might want me to post another question, but if we can do it here I figure we can save cluttering the forums with my obscure ideas!
Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
I'm not sure it will help but it might be that just setting `FILTER_SOURCE_FILES=YES` might help as the call / caller graphs are generated based on the results of same lexer that is used for `SOURCE_BROWSER = YES`. Note the current doxyge version is 1.13.2, but I don't think this has a lot of effect on your problem.
The limitations of using the MATLAB interface to SQLite are: NULL values are not supported as the first value in any column. Reference The possible workaround to use NaN insert(conn, 'example_table', {'id', 'name', 'age'}, {1, 'John', NaN}); where NaN is an empty string in the database
I am trying to launch a python script from within matlab. system('python3 /home/niuniek/meldog-ros/src/power_unit_v3/launch/power_unit_run_simulation_node.py') This script launches gazebo and a ros2 node for sending trajectories into a simulation. def launch_gazebo_simulation(): # Open a new terminal and launch Gazebo simulation p1 = subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', 'cd meldog-ros &amp;&amp; timeout 13s ros2 launch power_unit_v3 power_unit_v3_optimization.launch.py']) time.sleep(13) p2 = subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', 'killall ruby']) if __name__ == '__main__': # launch_gazebo_simulation() launch_gazebo_simulation() This python script executes just fine from a regular terminal, but when i try to launch the matlab program, gazebo does not launch and i get this error message: [ruby $(which ign) gazebo-2] Library error for [/usr/lib/x86_64-linux-gnu/libignition-gazebo6-ign.so.6.16.0]: /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5: undefined symbol: _ZN18QTextureGlyphCache8populateEP11QFontEngineiPKjPK11QFixedPoint, version Qt_5_PRIVATE_API [ERROR] [ruby $(which ign) gazebo-2]: process has died [pid 16310, exit code 255, cmd 'ruby $(which ign) gazebo -r -v -v4 empty.sdf --force-version 6']. I've tried launching Matlab from root and it didnt work, i also tried using a different terminal (xterm, terminator) to no effect.
I have a Matlab code under this form: clear all; close all; clc; clear variables; folder = fileparts(which(mfilename)); % Add that folder plus all subfolders to the path. addpath(genpath(folder)); data_folder="D:\Trucmuche\2024"; proportion_list=[1, 11]; mixing_times_list=["000", "015", "030", "060", "120"]; for i=1:length(proportion_list) this_prop=proportion_list(i); for j=1:length(mixing_times_list) rehash; this_mixing_time=mixing_times_list(j); browse_and_filter(data_folder, this_prop,this_mixing_time); disp("Success ! Moving to the next one !"); end end and the function is function browse_and_filter(root_folder, this_prop, this_mix_time) if isfolder(root_folder) disp(['Great ! The folder "', root_folder, '" exists.']); else disp(['Bad :-( The folder "', root_folder, '" does not exist.']); end % Get all rank_1 directories in the root folder rank_1_dirs = dir(root_folder); rank_1_dirs = rank_1_dirs([rank_1_dirs.isdir] & ~startsWith({rank_1_dirs.name}, '.')); disp({rank_1_dirs.name}); ... The problem is that, for the (two, but this even seems inconsistent) first iterations in the main code (the "ij" loop let's say), this works well and I get the following: "Great ! The folder "" "D:\Trucmuche\2024" "" exists." {'0716'} {'0717'} {'0718'} {'0719'} where these lasts are the (expected) outcome of disp({rank_1_dirs.name}); However, at some iteration, for some reason I don't understand, I get this "Great ! The folder "" "D:\Trucmuche\2024" "" exists." but the next line (i.e. the list of subfolders) remains empty which is not what I expect... There are surely workarounds to alleviate this since the outcome is the same at every iteration of the loop, I can refactor the code but still I was wondering why do I have this inconsistent behaviour ? I am doing a write operation at the end of the code of each iteration but not in "D:\Trucmuche\2024". Also, I added a one second pause after each iteration to alleviate the possible effect of writing operations but this did nothing. Any clue about that ?
@user2587726 no worries, glad it worked for you with that change
MatLab 2023a App Designer stuck when opening a .mlapp file created by 2024a
Segmenting Shortest Paths in Simple Virtual Reality Map Images
@Compo Thank you for taking the time to edit the question and providing a helpful comment. Can you clarify why I would use `/C` or `/K`? `/C` `/K` Reference: https://ss64.com/nt/cmd.html. If that somehow elevates privilege, I would encourage you to post an answer.
@Diusha That must be a Windows issue then. I can't reproduce that on my Mac. Each of the modifier keys results in an event. Maybe a Windows user knows how to fix that.
fp = fopen('Img.dat', 'rb'); data = fread(fp, 'float'); fclose(fp); data = reshape(data,[512, 512, 242]); theta = [0 15 0]; transl = [0 0 0]; tform = rigidtform3d(theta,transl); data_rotated = imwarp(data,tform,'cubic'); figure;imshow(data_rotated(:,:,180)',[]); I tried the above matlab code, where the inpute images in 'Img.dat' is as follows: However, there are horizontal stripes in the result, which is 'data_rotated', as shown below: The difference between the above two images is that the input image has a relatively uniform noise distribution, while the output image has an uneven noise distribution, with higher noise at the red arrow in the above figure, resulting in stripes in the image. This reason seems to be related to the interpolation method of the MATLAB function imwarp. So how to eliminate this phenomenon?
Most promising way in this case seems putting this question on matlab central and wait for a matlab developer getting along to help you. The developers are very active in matlab central community and may unveil undocumented functionalities. Sorry stackoverflow :-)
For clarity, I think the issue with the code is L147 and onwards. 'f12 = @(x1)...' On fig2, the boundaries between the groups just aren't there.
i have been trying to do it by defining the variables in python, like: target = sys.argv[0]; patient = sys.argv[1]
I have this data set which is recorded from 50 children with FMCW radar to detect their heart rate and respiration rate. I am using this data set and I want to just calculate the range FFT and after that applying Doppler FFT in one of the receivers of it. The size of raw data is 4 ** 512 ** 6,000, where 4 is the number of receivers, 512 is the number of samples of each frame and 6,000 (60 * 5 minutes * 20 frames per second) is the number of all the frames. I have the following code but the Doppler_fft of all the windows gives me the same peak and it seems that the heart is not moving at all. I have used the 30 second windows (which includes 600 frames of 1,200 chirps) and I'm sliding the window in each loop. According to the Range_FFT plot the maximum peak of range_fft is in the 37th sample so the Doppler_FFT_goal shows the doppler fft of the exact location of the target. close all clear clc %% Select Participant Number ( 1 - 50 ) ParticipantNum = 1; if ( ParticipantNum < 1 || ParticipantNum > 50 ) disp('Wrong Participant Number') return; end %% Set Parameters para = f_Parameter(); %% Read CSV Data % read radar rawdata fid = fopen(['Rawdata\FMCW Radar\Rawdata\Rawdata_' num2str(ParticipantNum) '.csv']); tstream = textscan(fid, '%d', 'Delimiter', ','); tstream = tstream{1,1}; streamsize = size(tstream,1)/para.AntNum; Rawdata = zeros(para.AntNum, streamsize); for i = 1:para.AntNum Rawdata(i,:) = tstream((i-1)*streamsize+1:i*streamsize); end fclose(fid); refBRFilePath = ['C:\mydata\Nihon Kohden\Heart Rate & Breathing Rate\Ref_Breath_' num2str(ParticipantNum) '.csv']; refHRFilePath = ['C:\mydata\Nihon Kohden\Heart Rate & Breathing Rate\Ref_Heart_' num2str(ParticipantNum) '.csv']; Ref_BR = csvread(refBRFilePath); Ref_HR = csvread(refHRFilePath); %% Reshape Radar RawData to Signal Processing RawData = reshape(Rawdata, para.AntNum, para.adcsample*para.chirploops, para.datalength); %% plot the first frame of the first RX antena t = 3.3333e-07:512/3000000/512: 512/3000000 *(20*60*5) ; figure(1) plot(t(1:512),abs(reshape(RawData(1,:,1),1,512))) hold on plot(t(1:512),imag(reshape(RawData(1,:,1),1,512))) title("the IF signal of the first frame and RX antena") legend("real part","imaginary part") ylabel("amplitude") xlabel("time") %% calculations of range % fft(exp(j*w0*t)) ==> 2*pi*delta(w-w0) ==> w0=2*pi*BW*tdelay / Tchirp % tdelay= w0* Tchirp / 2*pi*BW ==> tdelay = 2*distance / c % distance = w0 *Tchirp *c / 4* pi*BW %w0=2*pi*fbeat ==> distance(range) = fb*Tchirp*c / 2*BW %% range fft Mix= reshape(squeeze(RawData(1,:,:)),256,12000); N= 1024; Range_FFT = zeros(N,12000); for i=1:12000 Range_FFT (:,i) = fft(Mix(:,i),N); end Fs =para.samplerate; % Range_FFT = fft(Mix(:,1),N),1; %freq = linspace(0, para.fps/2, length(Range_FFT(1:N/2,1))); freq = (0:(N-1)/2)*(Fs/N); Range = (freq *para.c)/(2*para.freqslope); figure('Name',"one sided range fft of one chirp 1-20 vs range") plot(Range,abs(Range_FFT(1:N/2,1))); % doppler fft with 30 seconds windows Doppler_FFT_goal =zeros(12000-1201,1200); Doppler_FFT_useless =zeros(12000-1201,1200); for i=1:12000-1200 Doppler_FFT_goal(i,:)=fftshift(fft(Range_FFT(38,i:i+1199),[],2)); Doppler_FFT_useless(i,:)=fftshift(fft(Range_FFT(100,i:i+1199),[],2)); end freq_doppler = (1:1200)*(Fs/1200); velocity = para.lambda*(abs(freq_doppler))/ 2*pi*(2*para.tc) ; % v= (lambda*f) / 4*pi*Tc figure(5) plot(velocity,abs(Doppler_FFT_goal(1,:))); hold on xlabel("velocity (m/s)"); ylabel("the doppler FFT 0f chirps"); plot(velocity,abs(Doppler_FFT_goal(2,:))); legend("the first 30 seconds","the second 30 seconds") here is the files related to the first participant of data set,the article for this dataset and my code(edditor.m). https://drive.google.com/drive/folders/1-lnWeh7_26bcN0zCqhCjjHpvuNd2biSA?usp=sharing
For such a small example it's hard to definitively suggest what the fastest approach might be, presumably if this is too slow then your real input is significantly larger?
Doxygen cannot see `m2cpp` filter inside of container
But a 2D discriminant function cannot, in general, be written in the form f(x), you need to use `fimplicit` with f(x,y).
@CrisLuengo, I need the main loop. The program should interact with user and with a device via a COM port using a special protocol with time intervals. In this example, I added `plot` for the sole purpose: try to open the Figure window not after exiting the loop, but before
Well technically, as previously mentioned, it is good practice to doublequote arguments, that could be ```%SystemRoot%\System32\cmd.exe /D /C ""P:\athTo\myBatchfile.bat""```; _(one set for the `/C` argument and one for the batch file name)_.
FYI That’s not a nested function. In MATLAB, the term “nested function” has a specific meaning: a function defined inside the body of another function, where it has access to the parent’s variables.
Which version of doxygen are you using? (`PERL_PATH` has been removed in doxygen version 1.8.16, current version is 1.13.0) Furthermore the `PERL_PATH` didn't have anything to do with the `FILTER_PATTERNS`, here it is required to have the place of the perl executable in the system path or use `*.m=/usr/bin/perl /usr/local/bin/m2cpp.pl`
From the classificationdiscriminant docs, we have Const — A scalar Linear — A vector with p components, where p is the number of columns in X Quadratic — p-by-p matrix, exists for quadratic DiscrimType The equation of the boundary between class i and class j is Const + Linear * x + x' * Quadratic * x = 0 where x is a column vector of length p. You could work out all of the matrix coefficients for the quadratic term by multiplying and writing out x'Qx, which you've done (with or without realising) already for the linear coefficients. However, it's easier to just treat this as a matrix equation and write a function which accepts x1,x2,x3 and evaluates the boundary using the matrices. You can do this by making a local function fKLQ(K,L,Q,x1,x2,x3) which you can alias with your existing anonymous function handles f12 etc like so: f12 = @(x1,x2,x3) fKLQ( K12, L12, Q12, x1, x2, x3 ); h2 = fimplicit3(f12,[xmin xmax ymin ymax zmin zmax]); f23 = @(x1,x2,x3) fKLQ( K23, L23, Q23, x1, x2, x3 ); h3 = fimplicit3(f23,[xmin xmax ymin ymax zmin zmax]); f13 = @(x1,x2,x3) fKLQ( K13, L13, Q13, x1, x2, x3 ); h4 = fimplicit3(f13,[xmin xmax ymin ymax zmin zmax]); function f = fKLQ( K, L, Q, x1, x2, x3 ) x = [x1(:),x2(:),x3(:)]; n = numel(x1); if n == 1 x = x.'; end f = zeros(1,n); for ii = 1:n f(ii) = K + L.'*x(:,ii) + x(:,ii).'*Q*x(:,ii); end end The x1,x2,x3 inputs for fimplicit are either row vectors or scalars, so you have to handle that when forming x correctly - there might be a simpler way to do that than what I've shown but I believe it at least works like this. The output divides your clusters as shown. Note: there are still some warnings about vectorisation here, I believe that's something to do with how I've written the matrix multiplication, with MATLAB warning that the evaluation output might not be as expected. You could avoid this by explicitly adding each coefficient, or maybe there's some other formulation, but in the meantime I think it's benign.
I am writing a MATLAB program, (1) containing main loop and (2) using keyboard. However, they are don’t work simultaneously. Code function p fig=figure(1); set(fig,'KeyPressFcn',@myfun); % plot(1,1) %2 % drawnow %2 ex=0; % while ~ex %1 % % ... %1 % end %1 function myfun(~,event) disp(event.Key); end end works: Figure 1 window opens, and all keystrokes appear in command window. Open lines marked with %1, i.e. add the main loop, and start the script execution. Figure 1 window doesn’t open. Stopping the script execution with Ctrl-C, Figure 1 opens and keystrokes begin to appear in command window. Now open lines marked with %2 and start. The Figure 1 window opens, but there is no visible reaction to keystrokes. Stopping the script execution with Ctrl-C, all keystrokes that occurred between startup and Ctrl-C dump out into the command window. How can I make main loop and keystrokes response to work simultaneously?
How have you configured your Python environment in MATLAB? Is `ExecutionMode` in or out of process? https://www.mathworks.com/help/matlab/ref/pyenv.html — The `'OutOfProcess'` mode is designed for cases like this, where there’s likely a conflict in a library. You’re not passing data from the one to the other anyway, so there’s no advantage to in process execution.
Thank you for the comment Luis mendo.. Nevertheless.. I suppose something went wrong..I got this error message: DB = 3x5 cell array {1x1 cell} ... Index in position 1 exceeds array bounds. Index must not exceed 1. Error in untitled (line 8) result = sum(cell2mat(cellfun(@(x) x, DB)), 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (I didn't check the time that it take yet). Thank you for your reply. JJVVE
Previous issue with 3d discriminant and solution: https://stackoverflow.com/questions/79271633/plotting-outputs-of-3d-quadratic-discriminant-analysis-in-matlab/79284721?noredirect=1#comment139816256_79284721
Since the null space has dimension 1 (rank+nullity=number of columns and the rank of that matrix is definitely 3) any basis vector for that null space must be a constant multiple of another. Unfortunately that constant is a complex number, so not always easy to see. When, as here, the null space has dimension 1, the components of vectors produced by either software should be in constant ratio. In fact, for this particular form of matrix, the first three components of those vectors should be complex proportional to the last column of A.
Is cv.findEssentialMat using matlab in someway?
It would help (us and you) if you simplified the problem and tested your MATLAB code with specific inputs in isolation, within the MATLAB IDE so you can add breakpoints, debug, and see full error traces. That would likely address point **1.** where your code isn't behaving how you expect. For **2.** Presumably `VI` is within `spm_jobman` but we can't see that here, the previous point would help in debugging this too. By the time we're at **3.** this question is too broad, again we can't debug it here, I'd advise you run one of the problematic inputs within the MATLAB IDE and debug
Nothing comes in the logs it just crashes but when I trued to reduce the sample size it worked just fine but got another error where the results pointers are not aligned
I've got a program that computes the null space of a matrix using scipy null_space. My code works absolutely perfectly when the matrix is real but seems to contradict results in MATLAB for complex matrices. For instance, [[ 1. +0.j 0. +0.j 0. +0.j -0.28867513+0.5j] [ 0. +0.j 1. +0.j 0. +0.j -0.28867513-0.5j] [ 0. +0.j 0. +0.j 1. +0.j 0.57735027-0.j ]] when plugged into scipy.linalg.null_space gives, [[ 0.24235958-0.32852474j] [ 0.16333098+0.37415192j] [-0.40569056-0.04562718j] [ 0.70267665+0.0790286j ]] The exact same matrix in MATLAB gives, 0.2235 - 0.3134i 0.1596 + 0.3502i -0.4151 + 0.2949i 0.6636 + 0.0639i These are clearly not the same up to scaling, so what's happening ? Is scipy just not very accurate for complex matrices or am I doing something wrong ?? Again my code works absolutely perfectly when the matrices happen to be real. Thanks in advance !
Because you did not specify the word boundary, `'([a-zA-Z_]\w*)\>(?!\s*\()'`. The ``\>`` is the boundary for the end of the word.
I'm trying to use vlfeat to calculate MSER features and then input them as keypoints to perform SIFT description. My issue is, no matter how many keypoints, matlab crashes, I can't really understand why and I'm too new in this field to know more, any ideas? % Clear workspace and initialize clear; clc; close all; % Step 1: Load the image img = imread('footwear.jpg'); % Replace with your image file name if size(img, 3) == 3 grayImg = rgb2gray(img); % Convert to grayscale if it's an RGB image else grayImg = img; end % Step 2: Perform MSER detection mserRegions = detectMSERFeatures(grayImg); % Extract MSER locations and scales mserLocations = mserRegions.Location; mserScales = mserRegions.Axes; % Major and minor axes of MSER ellipses % Compute approximate scales using the geometric mean of axes numRegions = size(mserLocations, 1); scales = sqrt(prod(mserScales, 2)); % Geometric mean of axes orientations = zeros(numRegions, 1); % Default orientation (set to 0) % Limit the number of keypoints (to prevent excessive memory usage) maxKeypoints = min(500, numRegions); % Use at most 500 keypoints mserLocations = mserLocations(1:maxKeypoints, :); scales = scales(1:maxKeypoints); orientations = orientations(1:maxKeypoints); % Construct frames matrix for VLFeat frames = [mserLocations(:, 1)'; mserLocations(:, 2)'; scales'; orientations']; % Step 3: Set up VLFeat run('C:\Users\user\Desktop\ERGASIA\vlfeat-0.9.21\toolbox\vl_setup'); % Replace with your VLFeat path % Step 4: Compute SIFT descriptors using VLFeat try [~, descriptors] = vl_sift(single(grayImg), 'frames', frames); catch ME fprintf('Error during SIFT computation: %s\n', ME.message); return; end % Step 5: Visualize MSER regions and SIFT keypoints figure; imshow(grayImg); hold on; % Plot MSER regions plot(mserRegions, 'showPixelList', false, 'showEllipses', true); % Plot SIFT keypoints vl_plotframe(frames); title('MSER Regions and SIFT Keypoints'); hold off; % Display some statistics fprintf('Number of MSER Regions Detected: %d\n', numRegions); fprintf('Number of Keypoints Used: %d\n', maxKeypoints); fprintf('Size of Descriptors: [%d x %d]\n', size(descriptors));
@CrisLuengo, thank you, I will pay attention to the details you have made.
You can use the same logic as in the code that you use for one constraint. It is better to define an indexing variable, so you can use it in both sides of the assignment statement: ind = (B==1) &amp; (A&gt;=7) &amp; (A&lt;=9); % logical index of elements to be modified A(ind) = A(ind) + some_number;
How to Highlight the Difference Between Two Bar Charts in MATLAB?
Try modify your dart code like that: Pointer&lt;Double&gt; listToPointerDouble(List&lt;double&gt; sample) { final Pointer&lt;Double&gt; pointer = calloc.allocate&lt;Double&gt;(sample.length, alignment: 8); final nativeSamples = pointer.asTypedList(sample.length); nativeSamples.setAll(0, sample); return pointer.cast&lt;Double&gt;(); } Don`t forget to free your memory after is unnecessary. calloc.free(pointer);
Programmatically find the "Saved in Simulink version" for a .sldd object in Matlab/Simulink
There is also an "export code to mfile" option within the SaveAs menu which makes @il_raffa's suggestion a bit simpler if OP can re-open the app in the original version of their app
Ah ok thanks. I think they like to have questions answered. If you put this in an answer I'll accept it.
I would think about whether this is the best way to present your data, if that difference is what you want the reader to notice.
Due to certain dependancies I have to downgrade my Matlab from 2024b to 2022b. I am working in a conda environment with python 3.9.12 After trying to install matlabengine with: cd "matlabroot/extern/engines/python" python setup.py install I get this error: /opt/anaconda3/envs/myenv/lib/python3.9/site-packages/setuptools/_distutils/cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated. !! ******************************************************************************** Please avoid running ``setup.py`` directly. Instead, use pypa/build, pypa/installer or other standards-based tools. See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details. ******************************************************************************** !! self.initialize_options() /opt/anaconda3/envs/myenv/lib/python3.9/site-packages/setuptools/_distutils/cmd.py:66: EasyInstallDeprecationWarning: easy_install command is deprecated. !! ******************************************************************************** Please avoid running ``setup.py`` and ``easy_install``. Instead, use pypa/build, pypa/installer or other standards-based tools. See https://github.com/pypa/setuptools/issues/917 for details. ******************************************************************************** !! self.initialize_options() /opt/anaconda3/envs/myenv/lib/python3.9/site-packages/setuptools/command/sdist.py:122: SetuptoolsDeprecationWarning: `build_py` command does not inherit from setuptools' `build_py`. !! ******************************************************************************** Custom 'build_py' does not implement 'get_data_files_without_manifest'. Please extend command classes from setuptools instead of distutils. See https://peps.python.org/pep-0632/ for details. ******************************************************************************** !! self._add_data_files(self._safe_data_files(build_py)) error: The installation of MATLAB is corrupted. Please reinstall MATLAB or contact Technical Support for assistance. which didn't appear when I had 2024b. I have tried reinstalling 2022b and got the same error. I can't install outside the environment as I have python 3.12 which isn't supported by MATLAB 2022b.
You cannot do that. You can only use `system` to run a Python script (the function just says “run this in a terminal”). Interaction between Python and MATLAB needs to go through `pyenv` and the like.
There is another little nuisance. When Alt key is pressed, control is transferred to the Figure 1 menu and subsequent keystroke is processed not by my code, but by the menu. For example, if Alt was pressed (and released) and than I press ‘H’ key the Help submenu opens instead of my assignment for ‘H’. Is it possible to avoid?
Maximum number of function evaluations has been exceeded - increase MaxFunEvals option
@Wolfie Good idea, thanks! Edited into the answer
@Irreducible if you write `the [dsp.se] SE` in a comment, it shows up as "the [dsp.se] SE"
Did you look at intermediate values? `zx`, your zero crossings, is an empty array. Then `per` is NaN, and with a NaN initialization value you will never find a solution.
Thanks for doing that - it does seem to be the particular cause of the OP’s problem.
@Davide you could probably do something with `DT = delaunay( x, y ); trisurf( DT, x, y, z );` and instead of using `x` and `y` from a linearly spaced mesh you create a mesh from `p2 = interp1( 1:size(p,1), p, linspace(1,size(p,1),100) );` to create a finer-spaced set of points around the perimeter and create a finer mesh from the unique values in `p2`. The Delaunay triangulation should mean you can use a much lower resolution but the polygon edges can be included as triangular edges in the mesh, sorry this isn't a full solution but maybe a nudge in the right direction.
Identifying variables outside of function calls
I am working on a MATLAB project where I have two sets of data: 1- "No Reflection": Represents baseline coverage area values. 2- "With Reflection": Represents coverage area values with an additional reflection effect. I am plotting these two datasets as a grouped bar chart and I want to highlight the difference caused by the reflection. Specifically, I need the section of each bar corresponding to the difference (reflection effect) to be highlighted in a different color on top of the "No Reflection" bars. Example: For instance, if: "No Reflection" value for the first bar (QAM = 16) is 120 m². "With Reflection" value for the same bar is 160 m². I want to: 1- Plot a bar representing 120 m² (base value for "No Reflection"). 2- Highlight the difference (160 - 120 = 40 m²) on top of the blue bar in red (highlight for the reflection effect). I want to apply this on all the bars on the image that is on the right side. Any assistance, please? This is my code: close all; clear variables; clc; QAM = [16, 32, 64, 128, 256, 512, 1024]; %% m_CAP modulation % Beamsteering without reflection VEC_Beam_no_reflection_mCAP = [ 117.5491 75.1933 53.5396 38.3105 23.0815 13.5634 6.9007; % Theta = 10 118.2629 76.1452 54.0155 39.0244 23.0815 13.5634 6.9007; % Theta = 30 118.2629 76.3831 54.0155 39.5003 22.8435 13.5634 6.9007; % Theta = 45 118.2629 76.6211 54.2534 39.5003 22.8435 13.5634 6.9007 % Theta = 60 ]; % Beamsteering with reflection VEC_Beam_reflection_mCAP = [ 121.3563 77.0970 54.7293 39.7383 22.8435 13.5634 6.9007; % Theta = 10 141.1065 88.7567 61.6300 42.5937 24.2713 14.5152 7.8525; % Theta = 30 153.7180 95.6573 67.8168 45.6871 26.6508 14.5152 8.8043; % Theta = 45 160.3807 100.6544 69.7204 50.4462 28.7924 16.4188 8.8043 % Theta = 60 ]; %% DCO-OFDM modulation % Beamsteering without reflection VEC_Beam_no_reflection_OFDM = [ 91.3742 59.7264 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10 95.4194 58.2986 34.7412 25.9369 16.4188 10.7079 4.9970; % Theta = 30 89.4706 59.4884 44.4973 24.7472 16.4188 8.8043 4.9970; % Theta = 45 83.5217 69.4825 40.2142 28.7924 16.4188 10.7079 4.9970 % Theta = 60 ]; % Beamsteering with reflection VEC_Beam_reflection_OFDM = [ 94.7055 61.8679 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10 113.9798 69.7204 42.1178 28.7924 16.4188 10.7079 4.9970; % Theta = 30 115.6454 74.9554 55.6811 28.7924 16.4188 9.7561 4.9970; % Theta = 45 114.4557 88.7567 50.6841 34.5033 21.1779 11.6597 4.9970 % Theta = 60 ]; %% Combine Data for Bar Chart angles = [10, 30, 45, 60]; data_no_reflection = [VEC_Beam_no_reflection_mCAP; VEC_Beam_no_reflection_OFDM]; data_with_reflection = [VEC_Beam_reflection_mCAP; VEC_Beam_reflection_OFDM]; % Generate gradient colors for m-CAP (blue) and DCO-OFDM (green) mCAP_blue_gradient = [linspace(0.8, 0.1, 4)', linspace(0.9, 0.2, 4)', linspace(1.0, 0.3, 4)']; % Light to dark blue DCO_green_gradient = [linspace(0.7, 0.1, 4)', linspace(0.9, 0.4, 4)', linspace(0.6, 0.2, 4)']; % Light to dark green % Combine colors custom_colors = [mCAP_blue_gradient; DCO_green_gradient]; % Plot for No Reflection figure('Position', [100, 100, 800, 600]); b1 = bar(data_no_reflection', 'grouped'); for k = 1:length(b1) b1(k).FaceColor = 'flat'; b1(k).CData = repmat(custom_colors(k, :), size(b1(k).CData, 1), 1); end xticks(1:length(QAM)); xticklabels(string(QAM)); xlabel('QAM Order, M'); ylabel('Coverage Area (m²)'); title({'Coverage Area Without Reflection', 'm-CAP and DCO-OFDM'}); legend(["m-CAP \Phi_{1/2}=10°", "m-CAP \Phi_{1/2}=30°", "m-CAP \Phi_{1/2}=45°", "m-CAP \Phi_{1/2}=60°", ... "DCO-OFDM \Phi_{1/2}=10°", "DCO-OFDM \Phi_{1/2}=30°", "DCO-OFDM \Phi_{1/2}=45°", "DCO-OFDM \Phi_{1/2}=60°"], ... 'Location', 'Best'); grid on; % Plot for With Reflection figure('Position', [100, 100, 800, 600]); b2 = bar(data_with_reflection', 'grouped'); for k = 1:length(b2) b2(k).FaceColor = 'flat'; b2(k).CData = repmat(custom_colors(k, :), size(b2(k).CData, 1), 1); end xticks(1:length(QAM)); xticklabels(string(QAM)); xlabel('QAM Order, M'); ylabel('Coverage Area (m²)'); title({'Coverage Area With Reflection', 'm-CAP and DCO-OFDM'}); legend(["m-CAP \Phi_{1/2}=10°", "m-CAP \Phi_{1/2}=30°", "m-CAP \Phi_{1/2}=45°", "m-CAP \Phi_{1/2}=60°", ... "DCO-OFDM \Phi_{1/2}=10°", "DCO-OFDM \Phi_{1/2}=30°", "DCO-OFDM \Phi_{1/2}=45°", "DCO-OFDM \Phi_{1/2}=60°"], ... 'Location', 'Best'); grid on;
One dimensional quadratic discriminant analysis in matlab
@Compo Thanks for the clarifying example with the double quotes. Why is it best practice to use the double quotes? Just curious.
Loop and keyboard don’t work simultaneously
I would like this because if I take, supose, `n=50` points, then near the edges the plot loses its smoothness, and I was thinking that by considering also the points on the edges it's possible to smooth it.
What is the green? Is it something given, or something to be calculated?
How do I update pixelClassificationLayer() to a custom loss function?
Sum row values when first column data is equal
>> table2array(removevars(groupsummary(array2table(c), "c1","sum"),'GroupCount')) ans = 11 4 12 5 13 23 or >> [unique(c(:,1)),accumarray(findgroups(c(:,1)),c(:,2))] ans = 11 4 12 5 13 23
Solving differential equations with ode solvers and finite difference in Matlab
I have the following error while designing a basic charge controller using PV array instead of Constant dc source
Application Compiler: Not able to run this app to package Code and create an Executable in Matlab
The math function block can be set to calculate exp(u) = e^u, you can just use a gain block to first multiply your input by 2, then use the math block. If you really want this in a specific, single "block" then you can create a subsystem from the above blocks (CTRL+G or via the context menu when highlighted), then right-click > Mask > Edit Icon Image... and select your image. You could make this a mask such that you can configure the gain, or add it to a custom library so you can reuse it:
How to insert NULL values into a SQLite database table using MATLAB?
This question looks very similar to https://stackoverflow.com/q/78576265/16582 The big difference is that your segments are variable sizes. Given that you allow different segment sizes, what exactly are you trying to optimize? The number of segments, or something else? FYI here is the application I developed to solve the problem witch a fixed segment size https://github.com/JamesBremner/Mapify
It would be helpful if you stripped out the app bits of this code and just presented the standalone calculation function with example input values (which you're currently inputting via the app). Aside from that, the `while true` is very suspect when you're reporting your code is hanging, have you tried adding a breakpoint here to debug what's happening? How about adding an iteration counter and erroring after some number of iterations?
@simon, c'est la vie, but that's teamwork :-)
I don’t know if the answer below answers your question or not. Because it is unclear to me exactly what you are asking. If it does answer it, just give it the green tick mark and we can move on. Otherwise, please [edit] your post to include exactly what data structure you have and what you want to have. Preferably by including a bit of code that mocks up a representative example of the struct you currently have.
Thanks! Wow, that was simple. This is from timestamping the arrival of photons in two different telescopes pointed at the same star. Stellar Intensity Interferometry. We are looking for the near simultaneous arrival of two photons - one in each telescope. As the earth rotates and the star moves across the sky, the path differences from the star to each telescope changes. We have to offset this difference to find those that would have arrived simultaneously had the paths been identical. The actual numbers I add are in 1000s of picoseconds and channel 1 and 2 are scopes 1 and 2.
it seems like .mlapp not compatiable or has changed since version 2023a and I am not sure what kind of promblem it is. .mlapp seems to be a Matlab-specific format, not a normal text format, which makes it impossible for me to copy it to other computers (running different versions of Matlab) at will. Is there any information about compatibility between APP designer versions? I cannot accept the incompatibility of "source code (in binary format)".
I am trying to simulate a specific block in Simulink using MATLAB, specifically the block represented by the expression e^(2s). I want to create this block visually in Simulink. I found an image online that shows how this block looks, and I would like to replicate it in my Simulink model. However, I’m not sure how to create this block effectively. I would appreciate guidance on the steps involved in creating this block, including any specific parameters or settings I should use.
If you look closely, the second link you provide leads to the GitHub project mexopencv. The corresponding project provides MATLAB MEX functions that interface with hundreds of OpenCV APIs [and] is suitable for fast prototyping of OpenCV application in MATLAB, use of OpenCV as an external toolbox in MATLAB (quote from the project's README). The first link you provide, which leads to the official OpenCV documentation, does not mention MATLAB. So, to make it clear: No, "standard" OpenCV does not use MATLAB in any way. It is the mexopencv project that you found, which provides bindings between OpenCV and MATLAB.
How to divide a matrix in MATLAB into N^2 segments each with NxN elements?
Have you checked the help of `ifft` (see [ifft](https://de.mathworks.com/help/matlab/ref/ifft.html)), there is a paragraph how to convert the single-sided spectrum into a two sided spectrum.
Using Doxygen `1.9.8` in the setup described [here](https://stackoverflow.com/questions/79385264/doxygen-cannot-see-m2cpp-filter-inside-of-container). And I have set `FILTER_SOURCE_FILES = NO`. Why do you mention this configuration? Are you proposing that I set it and `SOURCE_BROWSER` to `YES` and then inspect my filtered MATLAB code?
@jeanjacquesvivde It works with `DB` as defined in your question; see [here](https://tio.run/##TcuxCoNAEITh/p5iSg8ssrsaI0EI4luIhcil0gSiBuHw2S@n22SqH4bvPSz914XQ1JWHb4lA3O04UkBZzFg56KpVgG5aJfjS7XeDY75lAvP5sIDVcQ5WxwVYHZeQfycEUScCUSc5RJ0UEHVSIosuQvNx8zouqDCvUzK4ceSpX854rq/kkWwWW4qmtjYFWWNC@AE)
Have you done what Cris suggested (i.e., verifying that the problem does not come from some code that you did not include in your question)? The code you posted cannot be the source of your problem, since it does the same thing for any `i` or `j` value
Matlab crashes after using vl_sift function with MSER-detected keypoints
MATLAB error when running python code with pyrunfile
If nothing else works, you can recover the code from the .mlapp file, this way (**make a backup copy before**): change the extension of the file from `.mlapp` to `.zip` then unpack it in a folder. Explore the folders, you can find the MatLab code in the folder "matlab" (it is a xlm file, remove the uncecessary text), a picture of the GUI in the metadata folder and so on.
I think you could try. See this post ['setup.py install is deprecated' warning shows up every time I open a terminal in VSCode](https://stackoverflow.com/questions/73257839/setup-py-install-is-deprecated-warning-shows-up-every-time-i-open-a-terminal-i)
Please add information via an [edit], not an an answer
Plotting a function inside a polygon in Matlab
I guess what you are missing is that you need to parse the command line arguments that you produce when you call `system()`. Python does not "magically" assign them to appropriate variables, but instead provides them via the `sys.argv` list. Try `import sys` and `print(sys.argv)` in your Python script to see if that gets you any further. Also see [here](https://docs.python.org/3/library/sys.html#sys.argv) for more doc on `sys.argv`.
You can use structfun to iterate over all of the fields in OPC_UA, and if the function you supply is just @(x)x then the node within that struct field will be returned. Since they're all scalar objects which can be concatenated into an array, they will be. Example setup: OPC_UA = struct(); OPC_UA.node1 = opcuanode(1, 'node1'); OPC_UA.node2 = opcuanode(2, 'node2'); OPC_UA.node3 = opcuanode(3, 'node3'); Using structfun to get all of the nodes into an array: nodes = structfun( @(x)x, OPC_UA ); A more verbose way of doing this which would let you be selective about which fields of OPC_UA you use would be something like this, looping over the field names with dynamic struct.(fieldname) syntax: fn = fieldnames( OPC_UA ); nodes = opc.ua.Node.empty(0,1); for i = 1:numel(fn) nodes(i,1) = OPC_UA.(fn{i}); end
how to operate on a Matlab vector A with a condition from vector B and a condition from the values of vector A
I'm using Doxygen to document a MATLAB codebase. Doxygen doesn't support MATLAB natively, so I am using the m2cpp.pl filter developed by Fabrice. The filter is good, but not good enough for Doxygen to automatically generate callgraphs and collaboration graphs. I have considered a few solutions. Improve the filter The most 'proper' option but unfortunately not worth my time. The filter is written in Perl, which I have almost no experience with. Moreover, I am documenting a legacy codebase that is unlikely to change and will soon be re-written in Python. Manually write DOT Doxygen generates diagrams by writing files in the DOT language, which are then rendered by Graphviz. I can add my own DOT files using the Doxygen \dotfile command. The DOT language is quite simple, so I can define the call &amp; collaboration graphs that I want manually. However, this is tedious and leads to a lot of duplicated code. Semi-manual approach I was wondering if there is a middle-ground approach. I'm imagining a command that tells Doxygen which functions are called. For instance, in the code below I propose a new Doxygen command \calls, which would manually tell Doxygen that main() calls foo() and bar(). I know this would be a DRY violation and therefore error prone, but it makes sense for my situation where I am documenting legacy code that is unlikely to change. Could I do this by making some simple edits to the filter? %&gt; \brief Demo function function result = foo() result = 1; end %&gt; \brief Demo function function result = bar() result = 1; end %&gt; \brief Demo function %&gt; \calls foo, bar function result = main() var_1 = foo(); var_2 = bar(); result = var_1 + var_2; end External callgraph generator This callgraph generator supports MATLAB and returns a DOT output, but I'm not sure how I would include it in my pipeline. I would have to automate some process where it generates dotfiles that are automatically pulled into Doxygen.
"recommended approaches" strays into asking for opinion-based answers or off-site resources, which are both off-topic. Could this be rephrased or put in terms of a specific example or problem you're facing implementing this so that we might be able to provide a concise, objective answer? It feels like you're talking about lots of things (what's running in MATLAB, how you're calling it from Python, ...) which might be irrelevant to what your core issue is, just running both MATLAB and Python on AWS? Have you tried to do either?
I changed to xfill = [xaxis; flipud(xaxis)]; yfill = [b; min(zaxis)*ones(size(b))]; patch(xfill,yfill,'r'); And it filled the area in between! Your comment gave me an idea. Thank you!
Ahh I see, thank you I missed those lines were different. Thank you!
You already got quite a few answers, but see if [this](https://stackoverflow.com/questions/20336288/for-loop-to-split-matrix-to-equal-sized-sub-matrices/20337173#20337173) helps
Thdnk you. But I've already tried this, and it only partially solves the problem. After pressing 'Alt', the first press of any letter goes nowhere (the second press gives the desired effect).
I added an answer with the `im2col` approach, which is very easy but probably quite slow. Not sure if it's worth adding it to your benchmarking
“I can't get the quadratic (aka curved) boundaries to plot correctly.” Do you get an error message? or a boundary that is not what you expect? Is the plotting bad or is the discriminant itself bad? It would be much easier on us if you could remove things that are not relevant to the question from your code, see [mre]. There’s a lot there and it’s hard to know what your problem might be.
Is that your complete Python script? Then the error shouldn't be too surprising: The variables `target` and `originalPatient` have not been defined in the Python script. Where should they come from?
Inverse Fast Fourier Transform from One-Sided Fourier Amplitude Spectra at Matlab
Your question is incomplete. What was the output or error message? What is the expected result? Does the same error occur when applying the same methods to other, simpler ODE systems? You are transforming implicit differential equations into a vector field, is the occurrence of singularities possible or impossible?
The result of imwarp function IN MATLAB has horizontal stripes
You need to add a breakpoint and step through your code, you must not be satisfying any of the `if` conditions so `YCOB` is never defined. Note that comparing doubles is always risky [see here](https://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab), you would be better using a tolerance around each value for `ZZ`
I think you just need to swap the order of concatenation for yfill, since you want b to align with xaxis in the original order and you can align fliplr(xaxis) with the min zaxis values. xfill = [xaxis, fliplr(xaxis)]; yfill = [b, min(zaxis)*ones(size(b))]; patch(xfill,yfill,'r'); For some dummy example: xaxis = linspace(0,10,7301); zaxis = rand( 1, 1376 ) - 1; b = sin( xaxis ) + xaxis; xfill = [xaxis, fliplr(xaxis)]; yfill = [min(zaxis)*ones(size(b)), b]; patch(xfill,yfill,'r');
@BillBokeey A lot of computation on the files in the subfolders of rank_1_dirs
Note that variable names starting with an underscore are not valid, but this looks like it allows them.
Well, yes, that is what you get when you interpolate pure noise. Interpolation is only valid when the signal is properly sampled. For that, you must have a band-limited signal. Noise is not band limited by definition. So you will never be able to interpolate it correctly. You can apply a smoothing filter before rotating to reduce this effect, but it will also make your image more blurry.
Thank you very much for you answer and the precious clarifications.
The only way I figure is writing an M-file that builds all the comments. Something like: generator.m --> pub.m --> html (origin) (file to Publish) (Published web page) My code example, myOwnSolution.m is: % My own solution clc, clear, close all syms s fprintf('I want to Publish a LaTeX Variable, randomly built.\n'); fprintf('Let''s say:\n'); a = randi([2,7]); b = randi([2,7]); P = [1,a,b]; % Coeffs are randomly selected symPol = poly2sym(P,s); disp('A pretty view of P(s), in the Workspace:') pretty(symPol); fprintf('\n\n') fileID = fopen('testPublishLaTeX.m','w'); fprintf(fileID,'%%%% Publish a LaTeX variable\n'); fprintf(fileID,'%% This is a Publish file in Matlab\n'); fprintf(fileID,'%%%% First Section \n'); fprintf(fileID,'%% Publish a LaTeX variable in a text line: $P(s)=%s$\n',latex(symPol)); fprintf(fileID,'%%%% Second Section\n'); fprintf(fileID,'%% Publish a LaTeX variable and expression in a ordered list:\n'); fprintf(fileID,'%%\n'); fprintf(fileID,'%% # A LaTeX variable: $P(s)=%s$\n',latex(symPol)); fprintf(fileID,'%% # A LaTeX expression: $F(s)=\\alpha^2$\n'); fprintf(fileID,'%%%% Third Section\n'); fprintf(fileID,'%% Publish a LaTeX variable and expression in a unordered list:\n'); fprintf(fileID,'%%\n'); fprintf(fileID,'%% * A LaTeX variable: $P(s)=%s$\n',latex(symPol)); fprintf(fileID,'%% * A LaTeX expression: $F(s)=\\alpha^2$\n'); fprintf(fileID,'%%%% Fourth Section\n'); fprintf(fileID,'%% Publish a LaTeX variable and expression as lone expressions:\n'); fprintf(fileID,'%%\n'); fprintf(fileID,'%% $$P(s)=%s$$\n',latex(symPol)); fprintf(fileID,'%%\n'); fprintf(fileID,'%% $$F(s)=\\alpha^2$$\n'); fprintf(fileID,'%%%% Fifth Section\n'); fprintf(fileID,'%% Publish a LaTeX variable with (not in) HTML format:\n'); fprintf(fileID,'%%\n'); fprintf(fileID,'%% \n'); fprintf(fileID,'%% \n'); fprintf(fileID,'%% This is my polynomial over s: \n'); fprintf(fileID,'%% \n'); fprintf(fileID,'%% \n'); fprintf(fileID,'%%\n'); fprintf(fileID,'%% $$P(s)=%s$$\n',latex(symPol)); fprintf(fileID,'%%\n'); fclose(fileID); myDoc = publish("testPublishLaTeX.m","html"); Now, I can view in the browser the file testPublishLaTeX.html, just created with the publish command.
Well, it seems that there is really no ideal solution to this problem. (·д·)
Yes, there is a function specifically for Least-Squares method. It is called lsqcurvefit 3-rd output argument gives the residuals (errors) you want. See help lsqcurvefit In your case initial_guess = [yr; per; -1; ym]; [s, resnorm, residual] = lsqcurvefit(fit, initial_guess, x, y); plot(x, residual) For the covariance I didn't find any method other then to compute it from the Jacobian (which is the 7th output arguments of lsqcurvefit): [s, resnorm, residual, flag, output, lambda, jacobian] = lsqcurvefit(fit, initial_guess, x, y); covariance = inv(jacobian' * jacobian) * resnorm / (length(y) - length(s)); Please check that this covariance formula is the one you want to compute. I hope this answers well.
Ok, let me rephrase that. You are calling `fimplicit`. The docs say “fimplicit(f) plots the implicit function defined by f(x,y) = 0.” https://www.mathworks.com/help/matlab/ref/fimplicit.html Thus, you need to give it a function of x and y, and you need to use both variables if you don’t want to draw a vertical line. If you want to draw y=x^2, you pass it f(x,y)=x^2-y. If you have a function in the form f(x)=x^2, then you need to use a different function to plot it. Try for example `fplot`. https://www.mathworks.com/help/matlab/ref/fplot.html
Please show us some code so we might be able to at least guess what's wrong, otherwise you've got a fairly detailed error message there, you likely need to improve the initial conditions going into the transfer function block because its initial derivative is not finite. You might find it helpful to read about creating a [mcve], or read [ask]
@lastchance yes, I updated the matrix through all examples, and re-ran the calculations
In a quick test I think using `cellfun` is slowing you down here, you could do something similar de-nesting with `{:}` and a `reshape` e.g. `sum(cell2mat(reshape([DB{:}],size(DB,1),[])), 1)`
I already asked also to MATLAB support the same question. However, I must say that with MATLAB 2023b that used to work within a COM application. I tried to rollback to 2023b, but now I get the same error there too. So I guess I have something misconfigured.
I have a Matlab file , which defines the variables in the Simulink model and then runs it. A Simulink.SimulationInput Object is used to this end. The code i have used is a simple one. simIn = Simulink.SimulationInput("Model"); simIn = simulink.compiler.configureForDeployment(simIn); simIn = setModelParameter(simIn,RapidAcceleratorUpToDateCheck="on"); input1 = 1; simIn = setVariable(simIn, "input1" , input1); simOut = sim(simIn); Running it in Matlab doesn't lead to any errors. However when i try to create an executable using Application Compiler, the following error message pops up Unrecognized function or variable 'input1'. Error using buildRacTarget Variable 'input1' has been deleted from base workspace. The only way for me to prevent this error is to define the variable in the command window beforehand i.e before running the Application Compiler to create the executable. However this is not a usefull solution for my purposes. I have tried multiple approaches like: Using the evalin and assignin functions Using a 2nd Matlab script called initial.m, which defines the variable input1 and then passes it into a .m (which is a function script with the definition function model(input1) that defines the Simulink.SimulationInput object and runs the simulink model. Once again, this works perfectly in Matlab and Simulink but cannot be compiled into an executable. However, these approaches haven't worked. My question is , how can I fix it? Why is the variable defined in the .m file being deleted? Why doesn't this problem occur when executed in Matlab and Simulink? Hope you can help me out. Happy Holidays!
I edited the comment. The word boundaries just look different there.
@flipSTAR Thanks a lot for the suggestion. I have posted the query on MATLAB Central also, hope I will get the solution from there.
How to invoke a .bat file with elevated privileges from MATLAB
Based on your code, you can achieve the same result with result = sum(cell2mat(cellfun(@(x) x, DB)), 1); or better (thanks to @Wolfie) result = sum(cell2mat(reshape([DB{:}], size(DB, 1), [])), 1); This converts your cell array of cell arrays into a numerical 2D array, and then sums along the vertical dimension. However, this is not likely to be much faster than your current code. The issue with your approach is not the code, but the data type. If possible, you should define your DB variable directly as a numerical 2D array. That way the code would be simpler and faster: result = sum(DB, 1);. Normally, cell arrays in Matlab are only used if the contents are not homogenous in size or in type.
Condition-based table column calculation
I don’t understand “I only want to use x1”. You are defining a function `f(x,y)`. You need to use both coordinates if you want to draw anything other than a vertical line. Also, your code in the question is ignoring the linear part, so you didn’t copy the example well enough.
I want to know if there are any ways to plot a given function with domain restricted to a polygon with given vertices, in Matlab. For example, how can i plot the function f =@(x,y) x.*y inside the polygon whose vertices are given by p1 = [0 0], p2 = [1 0], p3 = [2 2], p4 = [0 1]? I know there exists the function inpolygon but I have no idea on how to use it to plot a function only inside the polygon. Thanks in advance.
I both have a MATLAB licence and a Microsoft office license
Plotting outputs of 3D quadratic discriminant analysis in matlab
I tried to obtain the coefficients of B-spline matrix using the following code: function C_matrix = calculateBsplineCoefficientMatrix(s) % Number of input samples N = length(s); % Construct Alpha Values (Used in the Recursive Calculation) alpha_values = zeros(1, 10); alpha_values(1) = -1/4; for i = 2:10 alpha_values(i) = -1 / (4 + alpha_values(i - 1)); end alpha = alpha_values(end); b_i = -alpha / (1 - alpha^2); % Construct Forward Recursion Matrix (C_plus) C_plus = zeros(N, N); % Matrix to store forward recursion values C_plus(:, 1) = 1; % Initialize first column as 1 for k = 2:N C_plus(k, :) = alpha * C_plus(k-1, :); C_plus(k, k) = 1; % Set diagonal values to 1 for recursion steps end % Construct Backward Recursion Matrix (C_minus) C_minus = zeros(N, N); I_N = eye(N); % Identity matrix of size NxN C_minus(N, :) = b_i * (2 * C_plus(N, :) - I_N(N, :)); for k = N-1:-1:1 C_minus(k, :) = alpha * (C_minus(k+1, :) - C_plus(k, :));enter image description here C_matrix = 6 * C_minus; end s here represents the signal or sequence basically this code is created from the paper FastO-line interpolation by Dooley in pdf document(1). s = rand(1, 4); C_spline_matrix = calculateBsplineCoefficientMatrix(s); disp('B-Spline Coefficients Matrix Form:'); disp(C_spline_matrix); The Solution is B-Spline Coefficients Matrix Form: 1.7327 -0.4665 0.1333 -0.0333 -0.4665 1.7410 -0.4974 0.1244 0.1333 -0.4974 1.8564 -0.4641 -0.0666 0.2487 -0.9282 1.7321 Then I tried to calculate its quasi diagonal matrix using the following code: M = length(s); % Polynomial order or interpolation order % Compute Transformation Matrices T_mu = compute_TD(M); % Transformation matrix T_mu T_z = calculate_Tz(M); % Transformation matrix T_z % Ensure numerical stability T_mu_invT = inv(transpose(T_mu)); % Explicit inverse transpose of T_mu T_z_inv = inv(T_z); % Explicit inverse of T_z % Compute the quasi-diagonal matrix C_LCN C_LCN = T_mu_invT .*C_spline_matrix .* T_z_inv; % Display the final quasi-diagonal matrix disp('Computed C_LCN Matrix:'); disp(C_LCN); The solution of quasi diagonal matrix Computed C_LCN Matrix: 1.8384 0 0 0 -0.5937 -2.4397 0 0 0.1728 1.1772 0.8176 0 -0.0168 -0.2263 -0.3135 -0.0388 The relevant functions are given below: function Td1 = compute_Td1(M) % Create a matrix of binomial coefficients [I, J] = ndgrid(1:M, 1:M); binomials = zeros(M, M); for ii = 1:M for jj = 1:M if jj <= ii binomials(ii, jj) = nchoosek(ii-1, jj-1); end end end % Compute powers and combine with binomial coefficients powers = ((- (M - 1) / 2) .^ (I - J)) .* (J <= I); Td1 = binomials .* powers; % Debugging: Display Td1 matrix disp('Td1 Matrix:'); disp(Td1); end function Td2 = compute_Td2(M) % Compute the Td2 matrix Td2 = eye(M+1); for n = 2:M+1 for k = 2:n-1 Td2(n, k) = Td2(n-1, k-1) - (n-2) * Td2(n-1, k); end end Td2 = Td2(2:M+1, 2:M+1); % Debugging: Display Td2 matrix disp('Td2 Matrix:'); disp(Td2); end function TD = compute_TD(M) Td1 = compute_Td1(M); Td2 = compute_Td2(M); % Compute TD TD = Td1 * Td2; % Force symmetry in TD TD = (TD + TD') / 2; % Regularization for numerical stability TD = TD + 1e-8 * eye(size(TD)); % Debugging: Display TD matrix disp('Symmetrized TD Matrix:'); disp(TD); end function Tz = calculate_Tz(M) % Generate the Tz transformation matrix for Newton interpolation Tz = zeros(M, M); for i = 1:M for j = 1:i Tz(i, j) = nchoosek(i-1, j-1) * (-1)^(j+1); end end % Regularization for numerical stability Tz = Tz + 1e-8 * eye(size(Tz)); % Debugging: Display Tz matrix disp('Tz Matrix:'); disp(Tz); end The problem is the it does not match the values as solved in the paper Electronic letters. The solutions provided are: Lamb, David, Luiz FO Chamon, and Vítor Heloiz Nascimento. "Efficient filtering structure for spline interpolation and decimation." Electronics letters 52.1 (2016): 39-41. Dooley, S., Stewart, R., and Durrani, T.: ‘Fast on-line B-splineinterpolation’, Electron. Lett., 1999, 35, (14), pp. 1130–1131 Based on these papers solved the solutions by MATLAB please see whether the solution is correct or not?
What is happening in your `browse_and_filter` function after the call to `disp({rank_1_dirs.name});`?
i actually used pyenv("ExecutionMode","OutOfProcess"); but with or without it, nothing changes
Is there a reason you want to use this approach over `FuncAnimation`?
By the way, if Python is already loaded as in-process, you need to restart MATLAB to set the mode to out-of-process. AFAIK, you cannot switch from using Python in the one mode to the other within the same session.
your question is not clear. please explain little more
Start by using `traceback` to see what function is calling things like `.local` . Then set `debug` on all functions in the trace stack to see where you are passing data that is expected to have a `dimensions` attribute but doesn't.
https://in.mathworks.com/matlabcentral/answers/2173431-how-to-programmatically-find-the-simulink-saved-version-for-a-sldd-dictionary-object?s_tid=mlc_ans_email_ques I have an answer from Anay for the above question. Need to check if it works.
Glad, I could help. If there are angled paths, it is more complex indeed. But you already find significant angle changes, which could be indicators for your segment borders. ```polyshape``` let's you draw any kind of polygons by giving the endpoints in the right order. Maybe you'll ask a new question with such an example and we can try figuring it out.
@Compo I think you are indicating that `/C` is invoked and that the subsequent arguments passed to the function must in double quotes For example: cmd.exe /C "myBatchfile.bat". I think this is what `sprintf` does. That being said, `runas.exe` is new to me and seems to be a promising substitute for `cmd.exe`? https://ss64.com/nt/runas.html Not having any luck or maybe I missed something. Again, Thanks
I have two vectors. One with time information and one with channel information. For example, A has time values A = 1, 2.5, 2.7, 3, 4, 5, 6, 7, 8, 9, 10 and B has channel values B = 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 1 I wish to add a number to the elements of array A, only when array B == 1 and only when the value of those elements in array A are between 7 and 9 for example (A >=7 & A <=9). I know how to do it for one constraint, but not for the second one. For one constraint I would use A(B==1)=A(B==1) + "some number" I need to do this because the number I add will change depending upon the values in array A. I will eventually need to add numbers to every value in A if it is a channel 1 value. My arrays are moderately large - 10^8 elements, but I only need to use about 50 ranges in array A. The values are monotonically increasing, but not by regular amounts. If I can do it for one range, I don't mind looping on the other ranges.
Maybe you can try table2cell(varfun(@(x) sum(cell2mat(x),1),cell2table(DB))) and you will obtain the result presented like 1×5 cell array {[63 66]} {[69 72]} {[75 78]} {[81 84]} {[87 90]}
Does your shown `cmd.exe` command use either `/C` or `/K`? Even if you aren't specifying one, `/C` is default. Therefore, what I've told you is the correct syntax for what you've shown in your question, not an answer to your question. Of course, I'd want to know if you've considered not running `cmd.exe` directly, and perhaps using `runas.exe` to launch the batch file by name.
Hi, when I changed the "while true" command line in the CALCULATEButtonPushed(app, event) function to " for i = 1:10000 ", the normal depth worked without any problems, but this time when I put "0" in the SIDEINCLINATION(ZZ) box in the ciritcal depth calculation, it gives the error "Unrecognized function or variable 'YCOB'. When I put "1", the code works without any problems. If you have any advice on this, I would like to know.
Please re-read [mre]. You show us parts of the code that produce the problem, not the full code. You need to remove parts of your code you think are not relevant to the problem, then *run your code again* to verify it still causes your problem. *Then* you can post that reduced code here.
WIth regard to Doxygen versions, [corentinaltepe/doxygen](https://hub.docker.com/r/corentinaltepe/doxygen) runs version 1.9.5 and [hrektts/doxygen](https://hub.docker.com/r/hrektts/doxygen) runs version 1.8.17, so you're right that `PERL_PATH` is deprecated in both. I will remove it and the other deprecated configurations from my Doxyfile. However, I had thought it was relevant to `FILTER_PATTERNS` since the filter `m2cpp.pl` is written in Perl and therefore surely Doxygen needs access to a Perl installation to interpret it. I suppose it just uses the filter Shebang for this?
In Scilab, here is a solution without explicit for loop, provided that c's first column is already sorted: i = [c(2:$,1)~=c(1:$-1,1) ; %T]; tmp = [0 ; cumsum(c,"r")(i, 2)]; res = [c(i,1), tmp(2:$)-tmp(1:$-1)] yielding --> res = [c(i,1), tmp(2:$)-tmp(1:$-1)] res = [3x2 double] 11. 4. 12. 5. 13. 23.
Implementation of the parameters error in the Matlab program
You can combine reshape with permute, e.g. like so: reshape(permute(reshape(M, N,N,N,N), [1,3, 2,4]), N,N, N*N) The inner reshape has your intended "cells" split into dimensions 1 and 3, which permute shifts into dimensions 1 and 2. The outer reshape may be omitted, if you are ok with having a 4D matrix.
Well the first thing you should be aware of, if running `cmd.exe` with `/C` or `/K` arguments is that all of those arguments should be enclosed within a single set of doublequotes. For example: ```%SystemRoot%\System32\cmd.exe /D /C "Arg1 "Arg 2" Arg3"```. _The outer quote pair are removed by `cmd.exe`_. You will note that nested doublequotes do not usually require additional escaping. It is however best practice to doublequote each individual argument, and where necessary, ask the called command or utility to handle any required removal of those doublequotes.
How to sum data in 2nd column for same values in column 1: c = [11 1; 11 3; 12 5; 13 9; 13 11; 13 3] expected result is: r = [11 4; 12 5; 13 23] I know how to manage this using a loop but is there another easier way? In Matlab the function accumarray would work but is there something similar in Scilab?
I was trying to fit a data set into a sinusoidal function with the code below: data = importdata('analisipicco.txt') ; x = data(:,1) ; y = data(:,2) ; yu = max(y); yl = min(y); yr = (yu-yl); % Range of ‘y’ yz = y-yu+(yr/2); zx = x(yz .* circshift(yz,[0 1]) &lt;= 0); % Find zero-crossings per = 2*mean(diff(zx)); % Estimate period ym = mean(y); % Estimate offset fit = @(b,x) b(1).*(sin(2*pi*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit fcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function s = fminsearch(fcn, [yr; per; -1; ym]) % Minimise Least-Squares xp = linspace(min(x),max(x)); figure(1) plot(x,y,'b', xp,fit(s,xp), 'r') grid Where the elements of output parameter vector, s ( b in the function ) are: s(1): sine wave amplitude (in units of y) s(2): period (in units of x) s(3): phase (phase is s(2)/(2*s(3)) in units of x) s(4): offset (in units of y) But when I run the code with my set of data the command window show this: Maximum number of function evaluations has been exceeded - increase MaxFunEvals option. Current function value: NaN s = 1.0e+05 * 1.0466 NaN -0.0000 2.4885 I don't understand if my data are not fitting for a sinusoidal function or just the code is wrong for the sinusoidal fit. For acknowledge this is my data set: -200 183966 -192 189734 -184 195724 -176 201663 -168 207557 -160 213278 -152 219000 -144 224677 -136 229500 -128 236024 -120 241968 -112 247787 -104 252963 -96 257491 -88 261967 -80 267373 -72 273494 -64 278599 -56 281476 -48 282610 -40 283097 -32 283839 -24 284971 -16 286169 -8 287164 0 287968 8 288561 16 288626 24 288107 32 286967 40 285132 48 282828 56 279847 64 276296 72 272299 80 268080 88 263564 96 258926 104 254052 112 248894 120 243694 128 238177 136 232665 144 227143 152 221959 160 216874 168 211678 176 206540 184 201537 192 196748 200 192091 I'm sorry but I'm new to Matlab. Thank you in advance
If you weren't creating a grouped barchart you could make these as stacked bars instead, with the top part of the stack equal to the difference between the two. Since you are using a grouped chart, a simple approach would be to plot the taller bars first (with the whole bar red), then hold on and plot the shorter bars. You can set the HandleVisibility to off for the red bars so that they don't appear in the legend. It would look something like this from your example: f = figure('Position', [100, 100, 800, 600]); % Set "HandleVisibility" to off so these bars don't appear in legend b2 = bar(data_with_reflection', 'grouped','HandleVisibility','off'); for k = 1:length(b2) b2(k).FaceColor = 'flat'; b2(k).CData = repmat([1,0,0], size(b2(k).CData, 1), 1); % [1,0,0] for red bars end % Plot for No Reflection hold on; % To plot 2nd set of bars on top b1 = bar(data_no_reflection', 'grouped'); for k = 1:length(b1) b1(k).FaceColor = 'flat'; b1(k).CData = repmat(custom_colors(k, :), size(b1(k).CData, 1), 1); end grid on; xticks(1:length(QAM)); xticklabels(string(QAM)); title({'Coverage Area With Reflection', 'm-CAP and DCO-OFDM'}); legend(["m-CAP \Phi_{1/2}=10°", "m-CAP \Phi_{1/2}=30°", "m-CAP \Phi_{1/2}=45°", "m-CAP \Phi_{1/2}=60°", ... "DCO-OFDM \Phi_{1/2}=10°", "DCO-OFDM \Phi_{1/2}=30°", "DCO-OFDM \Phi_{1/2}=45°", "DCO-OFDM \Phi_{1/2}=60°"], ... 'Location', 'Best'); Output:
I tried to set the callbacks after the `plot`. It didn't change anything.
I am trying to plot the outputs of quadratic discriminant analysis in MATLAB. I have previously asked about Linear analysis (LDA question for reference), however, now I wish to investigate using quadratic discriminant analysis. For LDA I used fimplicit3 to plot the plain however this requires knowing the form of the equation for the function to evaluate. I am struggling to work out what this should be. The code below works for LDA, but when I change to QDA it is clearly incorrect (you will see when you run the code, the plains intersect the data) as it does not include the extra "quadratic coefficents" introduced by the QDA. I have tried a few things, all unsuccessfully, which I have omitted for clarity. In summary, what is the equation I need to pass to "fimplicit3" at line 135, 137, 139, to plot a curved plain? Is there a better way of doing this? Beneath the code sample I have included the equations for 2d linear and quadratic, in case this helps. clear clc close all %---------------------------- x1 = 1:0.01:3; r = -1 + (1+1)*rand(1,201); x1 = x1 + r; y1 = 1:0.01:3; r = -1 + (1+1)*rand(1,201); y1 = y1 + r; z1 = 1:0.01:3; r = -1 + (1+1)*rand(1,201); z1 = z1 + r; x1 = x1'; y1 = y1'; z1 = z1'; label1 = ones(length(y1),1); Tclust1 = [label1,x1,y1,z1]; %---------------------------- x2 = 4:0.01:6; r = -1 + (1+1)*rand(1,201); x2 = x2 + r; y2 = 10:0.01:12; r = -1 + (1+1)*rand(1,201); y2 = y2 + r; z2 = 10:0.01:12; r = -1 + (1+1)*rand(1,201); z2 = z2 + r; x2 = x2'; y2 = y2'; z2 = z2'; label2 = 2.*ones(length(y2),1); Tclust2 = [label2,x2,y2,z2]; %---------------------------- x3 = 5:0.01:7; r = -1 + (1+1)*rand(1,201); x3 = x3 + r; y3 = 13:0.01:15; r = -1 + (1+1)*rand(1,201); y3 = y3 + r; z3 = 13:0.01:15; r = -1 + (1+1)*rand(1,201); z3 = z3 + r; x3 = x3'; y3 = y3'; z3 = z3'; label3 = 3.*ones(length(y3),1); Tclust3 = [label3,x3,y3,z3]; %---------------------------- T = [Tclust1;Tclust2;Tclust3]; data = T(:,2:4); labels = T(:,1); %LOOCV n = length(labels); hpartition = cvpartition(n,'leaveout'); % figure() output = zeros(n,3); for qq = 1:n %training data idx_Train = training(hpartition,qq); data_Train = data(idx_Train,1:3); labels_Train = labels(idx_Train); %test data idx_Test = test(hpartition,qq); data_Test = data(idx_Test,1:3); labels_Test = labels(idx_Test); %train the model on the training data Mdlquad3D = fitcdiscr(data_Train,labels_Train,'Discrimtype','quadratic'); %apply to the testing data pred_lbl = predict(Mdlquad3D,data_Test); (qq/n)*100 end iscorrect=output(:,1)==output(:,2); accuracy_full = (sum(iscorrect)/length(iscorrect))*100; %plot data with boundaries ----------------------------------------------- data = T(:,2:4); labels = T(:,1); xmin = min(T(:,2)); xmax = max(T(:,2)); ymin = min(T(:,3)); ymax = max(T(:,3)); zmin = min(T(:,4)); zmax = max(T(:,4)); %group 1 and group 2 K12 = Mdlquad3D.Coeffs(1,2).Const; L12 = Mdlquad3D.Coeffs(1,2).Linear; Q12 = Mdlquad3D.Coeffs(1,2).Quadratic; %group 2 and group 3 K23 = Mdlquad3D.Coeffs(2,3).Const; L23 = Mdlquad3D.Coeffs(2,3).Linear; Q23 = Mdlquad3D.Coeffs(2,3).Quadratic; %group 1 and group 3 K13 = Mdlquad3D.Coeffs(1,3).Const; L13 = Mdlquad3D.Coeffs(1,3).Linear; Q13 = Mdlquad3D.Coeffs(1,3).Quadratic; figure() scatter3(x1,y1,z1,'g') hold on scatter3(x2,y2,z2,'b') scatter3(x3,y3,z3,'r') %THESE ARE CORRECT FOR LDA - HOW TO INCLUDE Qxx? Is there a better way %than fimplicit3? f12 = @(x1,x2,x3) K12 + L12(1)*x1 + L12(2)*x2 + L12(3)*x3; h2 = fimplicit3(f12,[xmin xmax ymin ymax zmin zmax]); f23 = @(x1,x2,x3) K23 + L23(1)*x1 + L23(2)*x2 + L23(3)*x3; h3 = fimplicit3(f23,[xmin xmax ymin ymax zmin zmax]); f13 = @(x1,x2,x3) K13 + L13(1)*x1 + L13(2)*x2 + L13(3)*x3; h4 = fimplicit3(f13,[xmin xmax ymin ymax zmin zmax]); title('Full data set') xlabel('x') ylabel('y') zlabel('z') legend('Data 1','Data 2','Data 3','Boundary 1 -> 2','Boundary 2 -> 3','Boundary 1 -> 3','location','eastoutside') % For reference: 2D linear: K = MdlLinear.Coeffs(1,2).Const; L = MdlLinear.Coeffs(1,2).Linear; f12 = @(x1,x2) K + L(1)*x1 + L(2)*x2; h2 = fimplicit(f12,[xmin xmax ymin ymax]); 2D Quadratic: K = MdlQuad.Coeffs(1,2).Const; L = MdlQuad.Coeffs(1,2).Linear; Q = MdlQuad.Coeffs(1,2).Quadratic; f12 = @(x1,x2) K + L(1)*x1 + L(2)*x2 + Q(1,1)*x1.^2 + (Q(1,2)+Q(2,1))*x1.*x2 + Q(2,2)*x2.^2; h2 = fimplicit(f12,[xmin xmax ymin ymax]);
@Cris happy for OP to clarify further, but I interpreted they're using [this `readValue` function](https://www.mathworks.com/help/icomm/ug/opc.ua.client.readvalue.html) where the 2nd input `nodeList` is an array of [`OPC UA Node` objects](https://uk.mathworks.com/help/icomm/ug/opc-ua-components.html#buzt5x8-2). In my answer I made a struct of such node objects, and then output them as a concatenated array which would be suitable for `readValue`, without having to list them individually as in OP's last line.
Thanks a lot for the answer! Just one question, I know that `inpolygon` can also return the indices of the points that lays on the boundary of the polygon. Is there a way to use this in order to represent the function f both on the intern of the polygon and on its boundary?
I am trying to add vertically the lists of a database like DB (see below) contained in a cell. DB={ {[11 12]} {[13 14]} {[15 16]} {[17 18]} {[19 20]}; {[21 22]} {[23 24]} {[25 26]} {[27 28]} {[29 30]}; {[31 32]} {[33 34]} {[35 36]} {[37 38]} {[39 40]}} I would like to get: [33 36] [69 72] [75 78] [81 44] [ 87 90 ] I tried with a 'for' loop (see below) ... but taking too much time. How could I do this with the minimum of 'for' loops or even better, without any loop? Thank you very much for your attention. sum=[ ] for j=1:5 sumi=0 for i=1:3 sumi=sumi+ c2{i,j}{1} end sum=[sum sumi] end
How to dynamically update a single plot for multiple iterations in Python (equivalent to MATLAB drawnow)?
If you already have the green path and just want to divide it in segments, I'd transform the coordinates of the green paths into a logical matrix. Then you can easily find the borders of the segment and display it as you want. matrixSize = 600; %Your green path 2 column vector xPositions = greenPath(:,1); yPositions = greenPath(:,2); %Transform to logical matrix greenPathMat = false(matrixSize); idx = sub2ind([matrixSize, matrixSize], yPositions, xPositions); greenPathMat(idx) = true; %Get border in x and y direction xBorders = diff(m,1,2); yBorders = diff(m,1,1); %Get Start and End xStart = find(any(xBorders==1)) + 1; xEnd = find(any(xBorders==-1)); yStart = find(any(yBorders==1,2)) + 1; yEnd = find(any(yBorders==-1,2)); %Check if there are any values at matrix borders to add them to start/end if any(greenPathMat(:,1)); xStart = [1 xStart]; end if any(greenPathMat(:,end)); xEnd = [xEnd, matrixSize]; end if any(greenPathMat(1,:)); yStart = [1; yStart]; end if any(greenPathMat(end,:)); yEnd = [yEnd; matrixSize]; end %Calc number of segments nbSegments = length(xStart) * 2; if length(xStart) == length(xEnd) nbSegments = nbSegments - 1; end %Display path in black and white imagesc(greenPathMat) set(gca,"YDir","normal") hold on colormap gray for ii = 1:floor(nbSegments/2) %Vertical segments plot(polyshape([xStart(ii) xStart(ii) xEnd(ii) xEnd(ii)],... [yStart(ii) yEnd(ii) yEnd(ii) yStart(ii)])); %Horizontal segments plot(polyshape([xStart(ii) xStart(ii) xEnd(ii+1) xEnd(ii+1)],... [yStart(ii+1) yEnd(ii) yEnd(ii) yStart(ii+1)])); end %If last segment is vertical if length(xStart) == length(xEnd) plot(polyshape([xStart(ii+1) xStart(ii+1) xEnd(ii+1) xEnd(ii+1)],... [yStart(ii+1) yEnd(ii+1) yEnd(ii+1) yStart(ii+1)])); end If you plot them one by one it looks like this. Is this what you want?
I appreciate then answer for clarification. I knew that link goes to github it is just I was confused because the function name was same in both places. So just wanted to post and get clarification from the communiy. Thanks again you have saved me from writing my own funtion ;)
As this is rather a signal processing question than a programming question I recommend to ask it at [DSP.se](https://dsp.stackexchange.com/questions)
Could you [edit] your question to include a [mcve] in each language, such that we can copy/paste your code and reproduce the result you're seeing?
I am using MATLAB Actxserver to generate an Excel spreadsheet. A portion of this code is used to generate a formula for determining if any values in a list are different. Below is an example MATLAB code c = cell(1,4); c{4} = "=IF(AND(EXACT(A1:C1,A1)),0,1)"; writecell(c,'test2.xlsx','UseExcel',true); However, when I open the Excel file, it replaces the function with =IF(AND(EXACT(@A1:C1,A1)),0,1) The addition of the "@" symbol breaks the function and causes the cell to display "#VALUE!". If I remove the "@" symbol in Excel, the function works as expected. How do I stop Excel from automatically adding the "implicit intersection" symbol? I tried using a find and replace function within MATLAB as shown below, and it does not solve the issue. The "@" re-appears. Excel = actxserver('excel.application'); WB = Excel.Workbooks.Open(oufFile,0,false); WS = WB.Worksheets.Item(1); WS.Range('A1:Z100').Replace("@","") WB.Save(); WB.Close(); Excel.Quit();
I think it's related to the in-memory module not seeing the updates. I get this often when I put a python module running under WSGI.. Need to restart the whole webserver.
I would like to update the content of an executable inside a generated executable MatLab file. The file is generated with MatLab/Simulink compiler. Why would I want to do this? Because I need to sign the content of all executable that run on my company pc. I know I can open the generated executable as a zip file. Inside I can update or add any file. I have found that there is a sig1.xml file that contains the sha512 encoded with base64. So I have updated the sha512 signature of the modified file. But I have an error when opening the executable: CTF archive is invalid Is there a global signature to update? Or anything else? Any advice is welcome!
One slightly faster approach is to reduce to a single loop, and pre-allocate the output: n = 2; s = NaN( 1, n*size(DB,2) ); for ii = 1:size(DB,2) col = vertcat(DB{:,ii}); s(n*(ii-1)+1:n*ii) = sum( vertcat(col{:}) ); end Note that n here is the number of elements within each cell, which in your example was 2.
Hi Wolfie, Thank you for your comment. Your example is exactly what I’m trying to do! However, when I changed the order of yfill (min(zaxis) * ones(size(b))and b), it gave me the same result. At first, I wondered if MATLAB might be confused because min(zaxis) is a constant value, but based on your example, I guess that’s not the issue. Could it be that the problem arises because b is not defined as an equation?
You posted two images that look identical to me. I don’t see any stripes.
Finally i did a restart of python as well as matlab and it works now. What I also tested is, that when i change something in the python code and want to run it with matlab, I always have to restart matlab such that the updated code gets properly executed, otherwise the "old" code gets executed, this was totally unexpected for me and somehow strange - any reason for this?
How to include a LaTeX expression in a web page built with the Matlab Publish?
The goal invoke .bat files with administrative privilege from MATLAB. The Windows user account is a member of the administrators group, however, invoking the date command to change the system date / time returns insufficient privilege and seems to require an "administrative" terminal. I am starting with the Andrew Janke solution and would like to run a .bat file that requires administrative privilege (date command is in the .bat file). I have successfully run simple batch files with commands known not to require privileges. The crux of the said Janke solution is: startInfo = `System.Diagnostics.ProcessStartInfo`('cmd.exe', sprintf('/c "%s"', batFile)); Is there an argument that be added to modify cmd.exe or elsewhere in the parentheses owned by System.Diagnostics.ProcessStartInfo. What is the syntax to elevate the privilege of call to cmd.exe? My Google search failed to turn up a simple solution. What I did find seemed to be on the right track but I would prefer a simple argument for the said function: How to start a Process as administrator mode in C#
@RPM For me, this is what I thought about presenting them, but if there is another creative idea to show them, I'll be happy to know.
In Simulink, I defined a Discrete State Space model. However it only has a an input port for u and another for y, but I need to track the state x. How can I do it without building a state observer (which in this case should not be needed since the input is generated from Simulink itself with step blocks)? Note that I cannot modify C to be eye(n) and D to be zeros(n,m), because the discrete system I'm working with comes from the minimal representation of an identified transfer function, so I cannot just modify the matrices because that would modify the underlying process too.
Note: I tried this with Octave, since I don't have a MATLAB license. As already hinted at in the comments, your communication between your MATLAB script and your Python script is missing two essential aspects: The handling of the inputs to the Python script within the Python script. The handling of the results from the Python script within the MATLAB script. Handling the inputs to the Python script This is the easier part: Calling system('python script.py argA argB') from MATLAB results in calling the Python script script.py with command line arguments argA and argB. From within the called Python script script.py, the command line arguments are available via sys.argv, which is a list of strings. Let's assume you have a Python script script.py with the following contents: ### Contents of 'script.py' ### import sys print(sys.argv) Call this script from the command line via the following call: $ python script.py argA argB Then your output will look as follows: ['script.py', 'argA', 'argB'] As you can see, all command line arguments are available as strings, prepended by the name (or path) of the called script itself. You can now actually make use of them from within your script; for example, convert them to numbers for calculations or, as in your case, use them as a name for a file to be loaded. Handling the outputs of the Python script This is the more tricky part, and I am not sure if mine is the best solution: Once you have done all the data processing in your Python script, you somehow need to get the results back to MATLAB. A very straightforward approach would be printing the results within the Python script and then capturing the outputs as part of the return value of the system() call in your MATLAB script. Let's assume you still have the Python script script.py, with the same contents as above. Additionally now, let's assume we have a MATLAB script script.m with the following contents: %%% Contents of 'script.m' %%% [status, output] = system('python script.py argA argB'); sprintf('From python: %s', output) Call this script from the command line via the following call (again, I am using Octave here): $ octave script.m Then your output will look as follows: ans = From python: ['script.py', 'argA', 'argB'] As you can see, we got the same output, but this time from the MATLAB script (and only from the MATLAB script). The MATLAB script captured the Python output in the output variable, then processed it (by prepending 'From python: '), and printed it again. Putting it all together into a (somewhat) more useful example We can use the same approach to pass not only strings but actual data. For this case we might want to write raw bytes to the output from within our Python script, then parse them from within our MATLAB script and convert them to a corresponding MATLAB object. The following example … (in MATLAB) sends a number n to Python as a command line argument; (in Python) creates an n×n square matrix containing the values 0,1,…,n²-2,n²-1 as a 2D Numpy array, then prints the raw bytes of the corresponding float64 values; (in MATLAB) captures the raw bytes and converts them to the corresponding 2D MATLAB array of double values. Python script script.py: ### Contents of 'script.py' ### import sys import numpy as np # Convert 1st argument to integer, then create square matrix of doubles with it num = int(sys.argv[1]) data = np.arange(num*num, dtype=np.float64).reshape(num, num) # Write resulting bytes to stdout sys.stdout.buffer.write(data.tobytes()) MATLAB script script.m: %%% Contents of 'script.m' %%% rows_cols = 3; [status, res] = system(sprintf('python script.py %d', rows_cols)); numpy_data = reshape(typecast(uint8(res), 'double'), [rows_cols, rows_cols])' Command line call of Octave and corresponding output: $ octave script.m numpy_data = 0 1 2 3 4 5 6 7 8 As you can see, the 2D array was successfully reinstantiated as the MATLAB array numpy_data. In reality, this might be trickier, of course: For example, if the Python script produces more outputs other than only the raw data that we are actually interested in, we need to filter out the parts that we are interested in (on the MATLAB side) or suppress all unrelated outputs (on the Python side). Also, getting the numbers of bytes, shapes, and orders of dimensions correct might not always be as straightforward as in the given example (note, for example, that here we needed to transpose the final MATLAB result).
@Davide trying to understand why you might want that - are you asking because you want to plot an outline to the surface? Most likely very few of the mesh points used in this approach actually lie _on_ the boundary, but depending what you're trying to achieve there is likely another approach...
Same as Wolfie! I had a vague idea but couldn’t turn it into a concrete solution. I really like this approach. Based on my experience, numerical matrices generally enhance MATLAB performance compared to using cells.
i encountered the problem that when calling a python function within the matlab environment, the return value from python is not recognized in matlab - i always get a py.NoneType as an output. Here my code, it is a code to send E-mails. I can see the print commands as an output in matlab but cannot capture the return values properly (always a py.NoneType in Matlab). When calling the function directly from python everything works fine. What could the problem be ? import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import os def send_email(gmail_user, gmail_password, to_email, subject, body, attachment_path): """ Send an email with an attachment using Gmail's SMTP server. Parameters: gmail_user (str): Your Gmail email address gmail_password (str): Your Gmail app password to_email (str): Recipient's email address subject (str): Subject of the email body (str): Body text of the email attachment_path (str): Full path to the attachment file """ try: # Create the email email = MIMEMultipart() email['From'] = gmail_user email['To'] = to_email email['Subject'] = subject # Add the email body email.attach(MIMEText(body, 'plain')) # Normalize the file path attachment_path = attachment_path.encode('utf-8').decode('utf-8') attachment_path = os.path.normpath(attachment_path) # attachment_path = attachment_path.replace("\\", "\\\\") print(f"Processed attachment path: {attachment_path}") # Check if the attachment file exists if not os.path.exists(attachment_path): print(f"Error: The file {attachment_path} does not exist.") return 'Name in Email not correct!'; # Open the file in binary mode and encode it with open(attachment_path, 'rb') as attachment_file: attachment = MIMEBase('application', 'octet-stream') # Generic MIME type, could be more specific attachment.set_payload(attachment_file.read()) encoders.encode_base64(attachment) # Extract filename from the path filename = os.path.basename(attachment_path) print(f"Attachment found: {filename}") # Add header for the attachment attachment.add_header('Content-Disposition', 'attachment', filename=filename) # Attach the file to the email email.attach(attachment) print(f"Attachment '{filename}' added successfully.") return 'yes' # Send the email using Gmail's SMTP server with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() # Secure the connection server.login(gmail_user, gmail_password) server.sendmail(gmail_user, to_email, email.as_string()) print("Email sent successfully!") return 'Email sent!' except Exception as e: print(f"Failed to send email: {e}") return 'Email failed fatal!' return "Unknown error occurred." Thanks in advance I tried a "mini example" with a simple python function (just adding two numbers) and it worked, so I have no idea why the more advanced code does not work. No errors are showing up in Matlab and also no details from the python code. My expectation was that when calling the function from Matlab like output=py.send_email.send_email(Arguments) The variable "output" holds the string 'Email sent!', but instead is always py.NoneType. I built in some print statement just to check if Matlab prints it properly, and it does ! The email is being sent as it should. I just want an output variable for some extra coding in Matlab. I also get no return when i use the wrong path where I should get 'Name in Email not correct!', and this is just at the beginning.
I am now creating a MATLAB script to read the release versions in which a sldd object is created in Simulink/MATLAB. For example, An SLX file activeSuspension.slx's matlab version it has been saved in can be retrieved using Simulink.MDLInfo object and it's property 'ReleaseName'. mdlInfo= Simulink.MDLInfo('activeSuspension'); matlabVersion=mdlInfo.ReleaseName; From documentation https://in.mathworks.com/help/simulink/slref/simulink.mdlinfo.html I am aware that MDLInfo is only limited to .slx,.slxp and .mdl files. Now coming to my query, I would like to know if there is any direct API command like MDLInfo or a resuable script available to get the matlab version created for a .sldd file. Since the metadata is visible in MATLAB UI for a .sldd file I believe there is a solid possibility to have an API command from which the "Saved in Simulink " version can be found, but I am unlucky so far to find one from documentation. Thanks in advance
Avoid "implicit intersection" symbol addition to Excel formulas when using MATLAB Actxserver
Could this help you? m = reshape(M,N,N,N*N);
Adding word boundaries fixes it: `(\b[a-zA-Z_]\w*\b)(?!\s*\()`
I am trying to automate the Doxygen documentation build for a MATLAB library using BitBucket pipelines. Doxygen doesn't support MATLAB natively, so I am using the m2cpp.pl filter developed by Fabrice. My Doxyfile is default apart from the following settings. FILTER_PATTERNS tells Doxygen to use the filter and PERL_PATH tells Doxygen where to find the installation of Perl needed to run the filter. EXTENSION_MAPPING = .m=C++ FILTER_PATTERNS = *.m=m2cpp.pl PERL_PATH = C:\Strawberry\perl\bin After some daft problems with relative filepaths etc, I was able to run this on my Windows laptop with the latest version of Doxygen and it produces the expected HTML files documenting my MATLAB library. Then I tried to repeat the same inside of a Docker Container, so that I can automate this process with BitBucket Pipelines. I have tried two Doxygen images: corentinaltepe/doxygen and hrektts/doxygen. I changed the filepaths accordingly and Doxygen runs 'fine' but produces blank documentation. EXTENSION_MAPPING = .m=C++ FILTER_PATTERNS = *.m=/usr/local/bin/m2cpp.pl PERL_PATH = /usr/bin/perl The Doxygen readout always includes sh: 1 /usr/local/bin/m2cpp.pl: not found. I get the same message when I run the container locally or through a pipeline. Moreover, I have even run the container in interactive mode and used the shell to check that the file is present. On one occaision, I had these consecutive lines in the terminal... root@6a1b63b93f6d:/# /usr/local/bin/doxy/m2cpp.pl bash: /usr/local/bin/doxy/m2cpp.pl: /usr/bin/perl.exe^M: bad interpreter: No such file or directory root@6a1b63b93f6d:/# ls -l /usr/local/bin/doxy/m2cpp.pl -rwxrwxrwx 1 1001 1001 6892 Jan 24 15:48 /usr/local/bin/doxy/m2cpp.pl ... where Line 2 says No such file and then Line 4 confirms I have rwx permission for the very same file. I have tried several different options for putting the file in different places, accessing it via different paths etc, and its always the case that the Doxygen readout says not found.
It can be fixed by using system('python [.py filename]') Thanks to @Cris Luengo for the solution
Try the following: Ensure MATLAB R2022b runs and extern/engines/python/setup.py exists. Install: pip install setuptools==58.0.4 wheel Install Engine: cd "matlabroot/extern/engines/python" python -m pip install .
avoid using `sum` as a variable name, you're shadowing the [in-built function](https://www.mathworks.com/help/matlab/ref/double.sum.html) which can cause unexpected errors
I cannot figure out why my Matlab code for extrapolating susceptibility using the reweighting method returns physically non-sensical graphs, even though the magnetization and energy series appear fine. Here's what the code looks like: load("M_abs.mat", "M_cb_abs1"); % normalized absolute magnetization load("E.mat", "E_cb1"); % normalized energy M = M_cb_abs1; E = E_cb1; global L beta_cr n_sample L = 20; % lattice size beta_cr = 0.41; % inverse critical temperature estimate N_cr = 3*10^5; % MC steps at beta_cr n_sample = 0.8 * N_cr; % post-thermalization MC steps beta_min = 0.3; beta_max = 0.6; del_beta = 0.01; betas=beta_min:del_beta:beta_max; % temperature range for reweighting chi = zeros(1, length(betas)); for i=1:length(betas) rw = reweight(M, E, betas(i)); [chi(i)] = deal(rw{:}); end function rw = reweight(M, E, beta) global n_sample beta_cr L delta = beta_cr - beta; sum1_M = 0; sum1_M2 = 0; sum2 = 0; for i = 1:n_sample w = exp(delta * E(i)); sum1_M = sum1_M + M(i) * w; sum1_M2 = sum1_M2 + M(i)^2 * w; sum2 = sum2 + w; end M_abs_avg = sum1_M / sum2; M2_avg = sum1_M2 / sum2; chi = beta * L^2 * (M2_avg - M_abs_avg^2); rw = {chi}; end The resulting graph is an almost linear, increasing function instead of the expected susceptibility peak at beta_cr.
The time shifting property of the Fourier transform states that the magnitude spectrum should not change, however, there should be a linear shift in the phase spectrum.
If you want to build a DLL with MinGW, you need to add `-shared` to the command line arguments of gcc.
Error: Arrays have incompatible sizes for this operation during Grad-Cam for 3D CNN (MatLab)
I'm trying to create a DLL from a set of MatLab scripts and a matching wrapper DLL (I need it to adapt functions calls/parameters to be used in LabView). Creating the DLL from the MatLab script goes pretty straightforward there are many examples, I got all the files that such compilation is supposed to produce (.dll, .h, .lib, .def etc). I followed a template for making the wrapper and the resuling source seems correct but when I try to compile it with this command: mbuild -v A0007121_3LIV_W.c A0007121_3LIV.lib LINKFLAGS="$LINKFLAGS /DLL /DEF:A0007121_3LIV_W.def" LDEXT=".dll" CMDLINE250="mt -outputresource:$EXE';'2 -manifest $MANIFEST" I got this: Verbose mode is on. ... Looking for compiler 'MinGW64 Compiler (C)' ... ... Looking for environment variable 'MW_MINGW64_LOC' ...Yes ('C:\mingw64'). ... Looking for file 'C:\mingw64\bin\gcc.exe' ...Yes. ... Looking for folder 'C:\mingw64' ...Yes. [..] Building with 'MinGW64 Compiler (C)'. C:\mingw64\bin\gcc -c -DMATLAB_DEFAULT_RELEASE=R2017b -DUSE_MEX_CMD -m64 -I"C:\Program Files\MATLAB\R2019b/extern/include" -I"C:\Program Files\MATLAB\R2019b/simulink/include" -I"C:\Program Files\MATLAB\R2019b/extern\lib\win64\mingw64" -I"C:\Program Files\MATLAB\R2019b\extern\include\win64" -fexceptions -fno-omit-frame-pointer -O2 -fwrapv -DNDEBUG "C:\Users\m.santucci\Documents\MATLAB\SIRIO\A0007121_3LIV\A0007121_3LIV_W.c" -o C:\Users\MAB0B~1.SAN\AppData\Local\Temp\5\mex_4521000822066357_3928\A0007121_3LIV_W.obj C:\mingw64\bin\gcc -m64 -Wl,--no-undefined,--out-implib,"A0007121_3LIV_W.lib" -s C:\Users\MAB0B~1.SAN\AppData\Local\Temp\5\mex_4521000822066357_3928\A0007121_3LIV_W.obj A0007121_3LIV.lib -L"C:\Program Files\MATLAB\R2019b\extern\lib\win64\mingw64" -lmclmcrrt -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 -o A0007121_3LIV_W.dll Error using mbuild (line 166) Unable to complete successfully. C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/6.3.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain' collect2.exe: error: ld returned 1 exit status I'm using MatLab 2019b, MinGW-W64 6.3.0 --- SOURCES --- Script source. function [SNR_dB, PhaseNoise_mean] = Misura_SNR_con_SBX(FullName, Figure_path) ... end Wrapper header. #ifndef A0007121_3LIV_W #define A0007121_3LIV_W void loadA0007121_3LIV(void); void unloadA0007121_3LIV(void); int wmlfMisura_SNR_con_SBX(char* FullName, char* FigurePath, double* SNR_dB, double* PhaseNoise_mean); #endif Wrapper code. #include "A0007121_3LIV_W.h" #include "A0007121_3LIV.h" #include "matrix.h" void loadA0007121_3LIV(void) { A0007121_3LIVInitialize(); } void unloadA0007121_3LIV(void) { A0007121_3LIVTerminate(); } int wmlfMisura_SNR_con_SBX(char* FullName, char* FigurePath, double* SNR_dB, double* PhaseNoise_mean) { int result = 1; mxArray* mFullName = mxCreateString(FullName); mxArray* mFigure_path = mxCreateString(FigurePath); int nargout = 2; mxArray* mSNR_dB = NULL; mxArray* mPhaseNoise_mean = NULL; //int nargout, mxArray** SNR_dB, mxArray** PhaseNoise_mean, mxArray* FullName, mxArray* Figure_path result = mlfMisura_SNR_con_SBX( nargout, &mSNR_dB, &mPhaseNoise_mean, mFullName, mFigure_path); //TODO: outputs ? memcpy(SNR_dB, mxGetPr(mSNR_dB), sizeof(double)); memcpy(PhaseNoise_mean, mxGetPr(mPhaseNoise_mean), sizeof(double)); mxDestroyArray(mFullName); mxDestroyArray(mFigure_path); mxDestroyArray(mSNR_dB); mxDestroyArray(mPhaseNoise_mean); return result; } Wrapper .def file. LIBRARY A0007121_3LIV_W EXPORTS loadA0007121_3LIV unloadA0007121_3LIV wmlfMisura_SNR_con_SBX I can share more details if needed. --- EDIT --- I tried to add an empty main to the wrapper C code: int main(int argc, char* argv[]) { } Now WinMain reference error has been fixed (!?) but I got this: 'mt' is not recognized as an internal or external command, operable program or batch file.
Converting MATLAB FFT-based Delay Function to CUDA MEX
The rpmfreqmap function in matlab has an input option resfor frequency resolution. With the output there is also a frequency resolution option res. If I specify a frequency resolution of 1 Hz: [map,freq,rpmOut,time,res]=rpmfreqmap(randn(1,100000),3000,linspace(1,100,100000),1,'OverlapPercent',0); With this the result will be res=1; as expected. But the frequency vector is freq(1:4)=[0 0.6665 1.3330 1.9996]. I would have expected freq(1:4)=[0 1 2 3]. Equally with no overlap I would expect the time vector to be time(1:4)=[0.5 1.5 2.5 3.5], but it is time(1:4)=[0.7502 2.2505 3.7508 5.2512]. So the relationship between frequency and time steps is delta_time=1/delta_freq, but it doesn't align with the specification in res. So, how can I derive the frequency step size of the output vector of rpmfreqmap?
I don't need to know where the CTF file is unpacked I need to know where the executable is run from the user... because this's a NON variable path.
@jdweng I corrected in the post. R opens MATLAB, displays the result but does not capture it and bring it to the R environment.
Issue with Shifting Aliasing Signal on Time Axis in MATLAB
There are many things possible using coder.ceval - including calling C++. But also many limitations. Currently working on this as well. You can call arrays, but there are limitations if you have typedefs that define array datatypes. For inputs and outputs look into the use of coder.rref and coder.wref So in your example function [a,b,c,d] = callingCcode (x,y) % init output by reference variables b = 0; c = 0; d = 0; a = coder.ceval('Ccode', coder.rref(x), coder.rref(y), ... coder.wref(b), coder.wref(c), coder.wref(d));
Is the pattern of your `L` matrix always periodic as in your example? I.e., could you compute `L = repmat(L_block, [3, 4])` or similar? (Not 100% sure if that is what you mean by "permuted block matrix")
@Reinderien it is a mixed integer linear programming. I provided the code.
You should have included all of this crucial information in the original question at the outset (and it is better to modify the question now since comments are ephemeral). This is like pulling teeth! If you expect to get meaningful help you **have** to provide all of the relevant information. The driver is what it is but knowing that and the physical hardware may provide a way to make it work with some intermediate piece of software acting as a shim. Unusual imaging hardware often has its peculiar quirks :(
@Cal Fireflies' solution is _not computing all of `C`_. It only computes its nonzero entries, as a colum vector. Do you need all of `C`, or only that vector? I assumed you needed to get all of `C` as a sparse matrix because your code does that
Is there any reason for you to believe the two lines are parallel, other that they seem to be so? Have you generated the points by some algorithm, such that the lines are parallel, or have you just selected the points such the lines are "visually parallel"? If the latter is the case, you can't expect such a high standard for parallelism as `abs(cross_product) < 1e-6` to be achieved; rather, your actual `abs(cross_product)` of `0.0631` seems decent.
I want to show two lines are parallel. In the following plot you can see that the two lines red and blue are parallel. But when I implemented in code, they are not showing as parallel. The MATLAB code for that %Parallel line segment clc; clear all; line_segments = [ 0.9226 5.1428 3.1123 5.2620; 1.3742 5.4433 3.3678 5.5230; ]; % Calculate the direction vectors for each line segment directions = [line_segments(:,3) - line_segments(:,1), line_segments(:,4) - line_segments(:,2)]; % Threshold for parallelism (to account for floating point precision) threshold = 1e-6; % Find parallel line segments parallel_pairs = []; for i = 1:size(directions, 1) for j = i+1:size(directions, 1) % Check if direction vectors are parallel cross_product = directions(i, 1) * directions(j, 2) - directions(i, 2) * directions(j, 1); if abs(cross_product) &lt; threshold parallel_pairs = [parallel_pairs; i, j]; % Store indices of parallel segments end end end % Display parallel line segments disp('Parallel line segments (by indices):'); disp(parallel_pairs); % Create figure figure; hold on; grid on; axis equal; xlabel('X-axis'); ylabel('Y-axis'); title('Line Segments Plot'); % Plot each line segment for i = 1:size(line_segments, 1) x = [line_segments(i, 1), line_segments(i, 3)]; y = [line_segments(i, 2), line_segments(i, 4)]; plot(x, y, 'o-', 'LineWidth', 2, 'MarkerSize', 8, 'MarkerFaceColor', 'b'); end legend('Line Segments'); hold off; I found parallel_pairs is empty. - What is the wrong in my code? How could I implemented it correctly? Thank you.
Error in ode45 and 'Events' of a Satellite Tracking Radar Model (MATLAB)
@Anonymous I've already tried that method but something is not working well.
Thanks for following up on my answer! Note that I used different points to define the objects. For legibility, I just used ints below 10 to define the planes. Even when I plug in the original values, however, my version returns different distances. This is due to errors in your `plane_points_to_coeffs` function. In defining x1, x2...z2,z3, there is a typo with y3: it should be `y3 = C(2)`.
The [MATLAB documentation](https://www.mathworks.com/help/matlab/ref/rgb2gray.html#buiz8mj-9) gives the coefficients used by `rgb2gray`, which are different from those in your code.
The (i , j)-th entry of the result matrix C can be seen as the vector product, without conjugation, of the i-th row of A (transposed) and the j-th column of B. So you can get all pairs of indices (i , j) from L and do that in a vectorized way: % Example data: m = 3; n = 4; v = 9; L = logical([0 0 1 0; 0 1 1 0; 1 0 0 0]); % m by n A = rand(m, v); B = rand(v, n); % Computation: [ii, jj] = find(L); % all pairs for which the result is needed C = sparse(m, n); % preallocate as sparse ind = ii + (jj-1)*m; % linear index from ii and jj C(ind) = sum(A(ii,:).'.*B(:,jj), 1); % actual computation If you only need a vector containing the relevant entries of C, instead of the whole matrix: % Computation: [ii, jj] = find(L); % all pairs for which the result is needed ind = ii + (jj-1)*m; % linear index from ii and jj c = sum(A(ii,:).'.*B(:,jj), 1); % actual computation
not sure what the overhead would be using `min(abs(x))` to make this work with any real array
How do i mix theese vectors into a matrix in Matlab?
MATLAB runs significantly slower after storing value in a global search
Shouldn't you be importing the XML and Exporting to XML? Your code is reading the stl.
I found the problem: the bitness of the application is forced to 32bit even if the AnyCPU model is applied if this checkbox is checked (it translate to Perfer 32bit)
As Tim says, please identify your camera and how it is connected. Likewise, please state your OS.
I am running two live scripts, let's call them main.mlx and sub.mlx. Below are MWEs. The main.mlx: dbstack().file sub The sub.mlx dbstack().file When running dbstack().file in a live script, a file name "LiveEditorEvaluationHelper(randomNumbers).m" is returned. If sub.mlx is run manually, it returns a different Live Editor file name than when main.mlx is run (which it should). When sub.mlx is called through main.mlx though, the same Live Editor file name is returned twice, which is obviously incorrect. I need to be able to get the "LiveEditorEvaluationHelper(randomNumbers).m" from sub through main. I have multiple subscripts, and the "LiveEditorEvaluationHelper(randomNumbers).m" changes everytime MATLAB is restarted, so running it once and then just saving the name as a variable is very impractical. Using f = matlab.desktop.editor.getActiveFilename also doesn't work, since the "active file" is main.mlx. I am assuming just calling sub.mlx through main.mlx doesn't activate the script, or at the very least isn't interpreted as a function, so it isn't added on the dbstack struct, but I can't seem to find a way around this. I have seemingly looked everywhere, and can't find an answer to this. I apologize in advance if the solution to this is glaringly obvious. Thanks for your help! --- SOME CONTEXT --- For educational purposes, I need to write my code in Live Scripts, where I have a script to simulate physical phenomena. This is divided up into subscripts based on parts of the simulation. I need to use the Live Script to be able to explain what several functions do and how they work. Some of these functions are in subscripts, but are also used in the main script. My main goal is thus to be able to call a function that is declared in a different live script, instead of in the script itself or in a separate .m function file. Bear with me, chaos is about to ensue. Just executing the subscript in the main.mlx like sub doesn't allow for subscript functions to be saved in the workspace, and thus can't be called in the main script. A work-around for this is creating myFunction.m in the same folder instead, so I can call the function in main.mlx that way. However, that only statically works when myFunction.m doesn't change. That's not the case: I want to be able to alter the function code in sub.mlx (where explanations, LaTeX equations and figures are present), and then dynamically update myFunction.m in the background, so that main.mlx can now call the updated function "seemingly" from sub.mlx. The algorithm I wrote to do this works perfectly if I manually run sub.mlx. However, if I then execute sub.mlx through main.mlx, the function doesn't work anymore. Find the code below. I have a strong feeling as to why this fails. function saveFunction(functionName) stack = dbstack; % Get the current script filename and line number scriptName = stack(2).file; % The file where the function is called % Open the script file fid = fopen(scriptName, 'r'); if fid == -1 error('Cannot open the file: %s', scriptName); end % Initialize variables to track lines currentLine = stack(2).line; % The line where the function is called linesToSave = {}; foundFunction = false; % Read the file and move upwards, starting just above the current line lineNumber = currentLine - 1; while lineNumber > 0 % Read the current line lineNum = 1; fseek(fid, 0, 'bof'); % Reset fgetl while lineNum < lineNumber fgetl(fid); % Skip the lines until the target line lineNum = lineNum + 1; end tline = fgetl(fid); % Check if we found a 'function' keyword in this line if contains(tline, 'function') foundFunction = true; linesToSave{end+1} = tline; % Save the line with 'function' break; % Stop since the full function definition has been found end % Add the line to the linesToSave list linesToSave{end+1} = tline; % Decrease the line number to move upwards lineNumber = lineNumber - 1; end % Close the file fclose(fid); % If no function was found, raise an error if ~foundFunction error('No function definition found in the script before the call.'); end % Save the collected lines to a text file with the functionName fileID = fopen(['Functions/', functionName, '.m'], 'w'); if fileID == -1 error('Cannot create the file: %s.m', functionName); end % Write the lines to the text file for i = length(linesToSave):-1:1 fprintf(fileID, '%s\n', linesToSave{i}); end % Close the output file fclose(fileID); disp(['Code saved successfully as Functions/', functionName, '.m']); end Provided a folder "Functions" already exist in the current folder and is added to the path, the function is called like % a function in sub.mlx function a = myFunction(b, c) a = b + c; end saveFunction('myFunction'); where it looks for the closest function above where it was called, and saves it accordingly. (Yes, I know this won't work with nested functions, that's fine.) As I said, this works beautifully when running sub.mlx. When executed through main.mlx though, the active file is main.mlx, not sub.mlx, and sub.mlx (and the actual .m file running in the background, "Live Editor Helper ...") is not added to dbstack. So, stack, scriptName and currentLine fail to deliver what they should. I have tried to alter this algorithm to make it work, but can't seem to fix it. Any help is welcome!
How to extend linearly independent vectors in the null space of a matrix to a basis of the null space with Matlab
How can I change my code to more accurately determine the damping matrix?
Why are you not using [`padarray`](https://www.mathworks.com/help/images/ref/padarray.html#d126e259129)? If you're intent on implementing this yourself, why are you not using matrix indexing rather than loops?
What is the box constraint in the output of a support vector machine in matlab?
I need to create a .NET assembly from a Matlab 2019b 64bit script and use it in .NET 4.8 application wrote in Visual Studio 2022 64bit . The script is pretty simple: function [SNR, PhaseNoise] = Measure_SNR_w_SBX(FullName, FigurePath) close all %%Do something with data in file FullName, calculate SNR, PhaseNoise and %%create a file FigurePath img end I created the assembly trough this command: mcc -W 'dotnet:myAssembly,myClass' -T link:lib Measure_SNR_w_SBX.m resulting in an assemply exposing, among others, this method: public MWArray[] Measure_SNR_w_SBX(int numArgsOut, MWArray FullName, MWArray FigurePath) { return mcr.EvaluateFunction(numArgsOut, "Measure_SNR_w_SBX", FullName, FigurePath); } The final usage will be an application where I cannot use MWArray or other Matlab types but I'm restricted to standard type (double, strings) so I defined a wrapper assemlby (.NET 4.8) that uses standard types parameters: public void Measure_SNR_w_SBX(in string FullName, in string FigurePath, out double SNR, out double PhaseNoiseMean) { MWCharArray mwFullName = new MWCharArray(FullName); MWCharArray mwFigurePath = new MWCharArray(FigurePath); MWNumericArray output = obj.Measure_SNR_w_SBX(2, mwFullName, mwFigurePath); SNR = output[0].ToScalarDouble(); PhaseNoiseMean = output[1].ToScalarDouble(); } Inside the wrapper I instantiate the Matlab produced assembly trough this: using myAssembly; using MathWorks.MATLAB.NET.Arrays; [....] obj = new myAssembly.myClass(); But when myClass is istantiated what I got is: System.TypeInitializationException: 'The type initializer for 'myAssembly.myClass' threw an exception.' which in turn collect three internal exceptions: TypeInitializationException: The type initializer of 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception. TypeInitializationException: The type initializer of 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception. BadImageFormatException: Attempt to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) Of course myAssembly, mwArray and wrapper assemblies are referenced into the application. Matlab runtime is installed and the Array assembly is placed here: C:\Program Files\MATLAB\MATLAB Runtime\v97\toolbox\dotnetbuilder\bin\win64\v4.0\MWArray.dll Also excluding the wrapper assembly and instantiating myAssembly directly into the application lead to the same result. And if I change the call order i.e.: MWCharArray fullName = new MWCharArray(txtDatFile.Text); MWCharArray figure_path = new MWCharArray(txtFigureFile.Text); var obj = new myAssembly.myClass(); output output = obj.Measure_SNR_w_SBX(2, fullName, figurePath); double snr = output[0].ToScalarDouble(); double phase_noise = output[1].ToScalarDouble(); The exception is thrown on the first line: MWCharArray fullName = new MWCharArray(txtDatFile.Text); i.e.: System.TypeInitializationException: 'The type initializer of 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception.' that's collecting: BadImageFormatException: Attempt to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) TypeInitializationException: The type initializer of 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception. How can I fix this?
I am rewriting some Code that is written in Matlab to C++ with the usage of EIGEN (in Windows 10, Visual Studio 2022). In one particular case I am having a huge performance drop with EIGEN which I am not able to fix. A minimal example is the following in Matlab: r = [1,2,3,4,5]; init = ones(9, 1); M = zeros(9, 5); tic for i = 1:1E6 M = repmat(init, [1, length(r)]); M = r.*M + init; end toc >> Elapsed time is 0.605376 seconds. In words: I am first replicating the column vector init to fill the matrix M. Then I am multiplying a row vector r elementwise to M and add init to it. My C++ Version looks like this: RowVector<double, 5> r = { 1.0, 2.0, 3.0, 4.0, 5.0 }; Vector<double, 9> init = {}; init.setOnes(); Matrix<double, 9, 5> M = {}; std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); for (int i = 0; i < 1E6; i++) { M = init.replicate(1, r.size()); M.array().rowwise() *= r.array(); M.array().colwise() += init.array(); } std::chrono::steady_clock::time_point terminate = std::chrono::steady_clock::now(); std::cout << "Duration:" << std::chrono::duration_cast<std::chrono::milliseconds>(terminate - start).count() << "[ms]" << std::endl; >> Duration:13130[ms] Obsiously Matlabs Version is way smarter than my C++ Version. What am I doing wrong? I guess it could have something to do with MKL which is used by Matlab. I installed MKL as well and it doesn't seem to have a performance impact at all in this case.
@3CxEZiVlQ : I just added the correct tag.
By the way, MATLAB has two releases per year, so the “a” or “b” in the release name is important. There is potentially as much difference between R2024a and R2024b as between R2024b and R2025a.
@StephenC This is obviously not true https://de.mathworks.com/help/matlab/matlab_external/passing-data-to-java-methods.html I think you can normally mix java and matlab
Thank you very much for your reply. I was thinking that maybe I'm not using Matlab's commands correctly. I'll still leave the question open for the time being, because one gets the feeling that I'm not the first to encounter this problem.
"it is not working correctly": Please provide details.
Solving Differential Equations in MATLAB's Symbolic Math Toolbox
Solid approach -- but do you think there would be a more efficient way using the 'periodicity' of L? For instance if L had the same number of ones in each row and column, you could potentially get the rows and columns needed and just do `C_tmp = A(rows,:)*B(:,cols)` before "expanding" `C_tmp` into `C`. But in the absence of a precise relationship like that, is there any other way to use the regular nature of `L` to speed things up?
Sorry, I corrected the points. Each A,B,C point is located in the same object. I want to use one of the groups of three points to create a plane. and then from point A of the other group, calculate the smallest distance to the plane and plot it.
I have a simple Simulink model that passes a constant variable to the workspace. I've converted the Simulink model to an exe-file using Simulink Coder (with grt.tlc as the target system file). However, I'm struggling to change the value of the constant myConstantValue and send it to the executable file. I don't want to compile every time when I want to change the value. I've tried several options, such as saving the new myConstantValue in a .mat file and calling it in MATLAB with system('MyModel.exe -p myConstantValue.mat'), or writing myConstantValue=100 to a .txt file and calling it with system('MyModel.exe -i input_params.txt'). Unfortunately, none of these methods work—the executable always uses the initial data. I've also tried changing various settings in the Code Generation settings of Simulink, such as setting the default parameter behavior to "Tunable", but this hasn't made any difference. Could you please help me figure out how to change the constant value and pass it to the executable file?
You didn't state the camera make and model.
It would make it slightly easier if the column headings in your Excel table were valid MATLAB names, so that they stay the same when read in as MATLAB table headers. Then you can simply read it in with tbl = readtable( 'mytable.csv' ); you can use this function with xlsx files too, optionally setting the sheet name and range to read. Then you could assign all of the variables to your workspace with something like % Loop over rows of the table for ii = 1:height(tbl) % assign variable to base workspace assignin( 'base', tbl.ParameterName{ii}, tbl.ParameterDefaultValue(ii) ); end It's often easier to manage your data if you have it in the model workspace, or at least a struct rather than lots of "loose" variables, but this should work if you just want something to let you quickly parameterise from your Excel table.
Please read [ask] and how to provide a [mcve]. Right now you haven't provided anything but a general description and requirement.
@Wolfie I tested both with R2022b and R2024b and both with `figure` and `uifigure` (same issue in all cases). I edited question accordingly.
Hi @Wolfie! I have appended some context to my question, I concede that this is probably quite a niche topic, or there might exist better ways to achieve what I'm trying to achieve. Any help is welcome!
How can I calculate the output frequency steps of the rpmfreqmap function in matlab
So reading between the lines, there is no way to get the 14bit raw data from the camera into Mathlab (a bit rubbish). Configuring the camera as 8bit is what I currently do, but I am losing half the data. So the short answer answer to the posted question is "no", irrespective of the camera etc.
You can set the default figure position using set(groot, 'DefaultFigurePosition', [x, y, width, height]) Ref this MATLAB Answers question: https://uk.mathworks.com/matlabcentral/answers/526580-change-de-default-position-of-plot You could set this on startup, or before you run some code, and optionally reset it when you're done (I believe it will reset on MATLAB restart anyway). You can get the position before changing it with pos = get(groot, 'DefaultFigurePosition');, you could also use the existing default to preserve the width and height whilst changing x and y.
I have created a code to obtain the stiffness and damping matrix of a bearing system using simulated data as the input. The stiffness matrix is giving reasonably accurate results but the damping matrix is way off. I have spent days trying to diagnose the problem but cant seem to figure it out. I am using the time-domain method and using the built in lsqcurve function in MATLAB and the equation shown equation to determine K and X where V is found using differentiation and displacement is given data input. %% Load Time History Data data = load('simdata.mat'); % Time vector time = data.toutseconds_captured(:); % Measured dynamic forces (Fx, Fy) Fx = data.FBh_dynamic_from_MB(:); Fy = data.FBv_dynamic_from_MB(:); F_measured = [Fx, Fy]; %% Compute Velocities by Integration fsamp = 10e3; % Sampling frequency (should be sufficiently high) ttesti = 0:1/fsamp:time(end); % Define uniform time grid % Interpolate acceleration signals for finer resolution Xx_interp = interp1(time, data.xBrelJ_dynamic, ttesti); Xy_interp = interp1(time, data.yBrelJ_dynamic, ttesti); X = [Xx_interp; Xy_interp]; % Compute velocity by numerical integration dt = mean(diff(ttesti)); Vx = [0, diff(Xx_interp) / dt]; Vy = [0, diff(Xy_interp) / dt]; V = [Vx(:), Vy(:)]'; % Interpolate force signals to match uniform time step Fx_interp = interp1(time, data.FBh_dynamic_from_MB, ttesti); Fy_interp = interp1(time, data.FBv_dynamic_from_MB, ttesti); F = [Fx_interp(:), Fy_interp(:)]; F = F(:); % Initial guess for parameters (8 elements: 4 for C, 4 for K) params_initial = [300 100 100 300, 10e3 10 10 10e3]'; % Initial guess for K % Define the model function force_model = @(params, input_data) compute_predicted_force(params, input_data); % Use lsqcurvefit to estimate parameters options = optimoptions('lsqcurvefit','Display','iter'); % Display iteration inf % Combine displacement and velocity into a single input array input_data = [X', V']; params_estimated = lsqcurvefit(force_model, params_initial, input_data, F, [], [], options); % Extract estimated matrices C_est = reshape(params_estimated(1:4), [2,2]); % Damping matrix K_est = reshape(params_estimated(5:8), [2,2]); % Stiffness matrix disp('Estimated Damping Matrix (C):'); disp(C_est); disp('Estimated Stiffness Matrix (K):'); disp(K_est); %% Function to Compute Predicted Forces function F_est = compute_predicted_force(params, input_data) X = input_data(:, 1:2)'; V = input_data(:, 3:4)'; C = reshape(params(1:4), [2,2]); % Extract damping matrix (2x2) K = reshape(params(5:8), [2,2]); % Extract stiffness matrix (2x2 F_est = (K * X) + (C * V); % F_est: column vector for lsqcurvefit F_est = F_est'; F_est = F_est(:); end This is the code I have thus far and the outputs are current damping and stiffness matrix however the results I am hoping to be closer to are accurate stiffness and damping matrix, thanks Additionally, these are the frequency domain analysis graphs produced for force in X and Y direction. Freq-domain analysis - Y direction. enter Freq-domain analysis - x direction description here
Causality error in PLL linearization simulink
Reposting Bill's comment from proving ground: _"How big are m, n, and v? It will be hard to beat A*B. If you compute C = A*B you can index the values you seek with D = C(L) if L is logical, or D=C(logical(L)) if L is numeric containing 0s and 1s"_
I need to solve one LP per thread at the same time. I'm coding in Matlab and using gurobi as a solver. Since gurobi is an API that actually run calculations in C++, I'm unable to use several threads at the same time, despite that Simplex be a single thread algorithm. I tried the parfor function, but I got the MEX function error ("Use of MEX functions is not supported on a thread-based worker."). I would like to highlight that those LP are similar and I can't build one big problem with all of them since some can be infeasible. So, build one big LP and solving using barrier (which is multithread) is not an option. Is there any way (using gurobi or something else, even other programming language) to handle that? I tried to solve that using parallel toolbox from Matlab, however, since gurobi is a MEX function, I'm unable to assign one thread to each LP simultaneously. I would like to know if someone knows a way to do that, even if it using other programming language and/or solver.
Yes, you're looping through that list. But you're not indexing into the matrix, you're only looking at the array of indices. To index into a sparse matrix you need to do a binary search on the array of column indices, then a binary search on the array of row indices for that column. Finally, if your desired element is there, you need to read in array that stores the values to find the result of the indexing operation.
Matlab: how to unstack a table and filter reslting matrix
As an aside: `setx PATH "$env:Path;..."` is best avoided for persistent updates: while it _may_ have no (immediate) ill effects, it definitely _can_: `setx.exe` has a hard 1024-character limit, and replaces the original `REG_EXPAND_SZ` value with a `REG_SZ` value if the new value happens not to contain _unexpanded_ environment-variable references. Additionally, you're _duplicating entries_ by basing your new value on the process-level value of `$env:Path`, which is a _composite_ of the system-level and the user-level definition and only contains _expanded_ values.
You can try using the "Matlab in VSCode" extension (shinyypig.matlab-in-vscode) along with the official MathWorks extension, which will allow you to run the active cell. Excerpt from the official extension documentation. Check this for more information. Cell Mode You can split your code by %%, click the run cell button, or simply press ctrl+enter (Mac: cmd+enter) to run the active cell.
Pre-allocating as a full matrix would make this faster, if it fits in memory.
I'm trying to apply the Grad Cam technique to a 3D CNN (ResNet101). To do this, I'm trying to use the following code: dlImg = dlarray(single(img), 'SSSCB'); softmaxName = 'sofctmax'; featureLayerName = 'res5c_relu'; dlScores = predict(dlnet, dlImg); YPredScores = extractdata(dlScores)'; [score, classIdx] = max(YPredScores, [], 2); classfn = categorical(classIdx, 1:numel(categories(YTrue)), categories(YTrue)); [featureMap, dScoresdMap] = dlfeval(@gradcam, dlnet, dlImg, softmaxName, featureLayerName, classfn); function [featureMap,dScoresdMap] = gradcam(dlnet, dlImg, softmaxName, featureLayerName, classIdx) [scores,featureMap] = predict(dlnet, dlImg, 'Outputs', {softmaxName, featureLayerName}); classScore = scores(classIdx); classScore = extractdata(classScore); dScoresdMap = dlgradient(classScore,featureMap); end But I get this error in the dlfeval line: Arrays have incompatible sizes for this operation. If I run only my gradcam function the error changes because of dlgradient: Value to differentiate is not a dlarray. It must be a traced real dlarray scalar. My classScore is a single number and my featureMap is a 5-D dlarray witha size of 7 7 1 2048 1. What am I doing wrong? Thanks in advance.
you're assuming I'm deploying data togheter with matlab script executable ... this's not what's happening.. I simply need to know where the exe is located because this will be the folder where data are actually deployed.
How it is possible to solve one LP (Simplex) per thread in parallel?
@Yunnosch You are all right! SO SORRY! I am not that pro! (but humble enough ;-) )
MATLAB: How to calculate the distance between a plane and a point
the output is not going to standard output. Try without the -r which creates a report (file).
Is it possible to have a block with multiple outputs which also calls C code in Matlab Simulink?
Registration/alignment of two medical data STL files in Matlab
When you construct a table, the table variables only pick up the names from the names of the input workspace variables if you don't perform an operation on those input workspace variables. (In that case, you're effectively passing in to the table constructor unnamed temporary arrays). You can either: Operate on the arrays up-front and store them back in named variables that you pass directly to the table constructor, or Radii = Radii'; SurfaceA = SurfaceA'; Volume = Volume'; Sphere3 = table(Radii,SurfaceA,Volume) Use the name-value argument VariableNames=["Radii", "Surface A", "Volume"]) Sphere2 = table(Radii', SurfaceA', Volume', ... VariableNames=["Radii", "Surface A", "Volume"])
Ohhhh... I see. Thank you! That makes a lot of sense :)
If the performance is important consider generating the 3D arrays in the form of `[binNum * xdim * ydim]` and `[maxElementNum * xdim * ydim]` for `input_hist` and `output_values` respectively. In this case there is no need to perform permute and ipermute.
% A(2,2) A(2,1) A(2,1) A(2,2) A(2,3) A(2,3) A(2,2) % A(1,2) A(1,1) A(1,1) A(1,2) A(1,3) A(1,3) A(1,2) % 0 0 1 2 3 0 0 % 0 0 4 5 6 0 0 % 0 0 7 8 9 0 0 % A(3,2) A(3,1) A(3,1) A(3,2) A(3,3) A(3,3) A(3,2) % A(2,2) A(2,1) A(2,1) A(2,2) A(2,3) A(2,3) A(2,2) Hello, I am working on implementing symmetric padding using a for loop in MATLAB. However, it is not working correctly, so I have a question. Matrix A is a 3×3 matrix, and P is a 7×7 matrix. I want to map the coordinates of A to P, filling the values in P according to this diagram of padman, starting from P(1,1) to P(1,7). Could you please help me with how to implement this? Thank you! A=[1, 2, 3; 4, 5, 6; 7, 8, 9] size = size(P,1) m=2 %padding size for i = 1 : m %upper for j= 1 : size P(i,j) = A( ) end end for i= 1 : m %down for j= 1 : size P(i+size-m,j) = A( ) end end
Hi Ferror, thank you for your answer. But it is still not working. The command set_param cannot call the exe-file, and if I use the command system('test.exe -p constantValue.mat') % I save the new value of myConstantValue inside the mat-file. I still only get the initial value that has been used to compile the Simulink model.
Also, why are the values to the left and to the right of the central matrix zeros rather than than the reflected values?
Incoherence when using Matlab's lsim regarding continuous and discretized transfer function models
Find the page in a 3D matrix that is closest to a given matrix
When using sparse matrices, it's easy to find non-zero entries quickly (as these are the only elements stored). However, what's the best way to find the first ZERO entry? Using approaches like find(X==0,1) or find(~X,1) tend to be slow as these require the negation of the whole matrix. It doesn't feel like that should be necessary -- is there a better way? For instance, naively iterating over the array seems to be slightly faster than using find(X==0,1): % Create a sparse array [10% filled] x = sparse(5000,1); x(randsample(5000,500)) = 1; nRuns = 1e5; % Find the first element, a million times idx = zeros(nRuns,1); tic for n=1:nRuns idx(n) = find(x==0,1); end toc %% % Create a sparse array [10% filled] x = sparse(5000,1); x(randsample(5000,500)) = 1; nRuns = 1e5; % Find the first element, a million times idx = zeros(nRuns,1); tic for n=1:nRuns for kk = 1:numel(x) [ii,jj] = ind2sub(size(x), kk); if x(ii,jj)==0; idx(n) = ii + (jj-1)*n; break; end end end toc But what is the best way to do this?
How to create custom reinforcement learning agent in matlab and training with Simulink environment
How to Prevent issues in a Holt-Winters Forecasting Model with High Smoothing Parameters?
Simulation of radar images based on a simulated wave field
Data conversion between java and matlab buggy?
@magnesium I don't see how the structure of `L` can help. Regardless of the structure, if `L` has, say, _k_ `true` entries you need to compute `k` "vector products". I don't see how a particular distribution of those entries in `L` could help; unless they formed a rectangle, in which case everything would reduce to (sub-)matrix multiplication, but that's not the case in your problem. So, why do you think structure in `L` could help? Maybe I'm missing something. Also, when you say _potentially get the rows and columns needed_, that's what my code does, specifically with `ii` and `jj`
In the MathWorks coder.ceval documentation, I noticed this: ' Variables to hold nonscalar output can be passed by reference to the called C/C++ function by using coder.ref or coder.wref'. It seems that the called C/C++ function can only return a single scalar output with coder.ceval though, right?
Your answer contains useful information, but it doesn't actually answer my question, which is a yes/no question. I prefer direct answers to questions, so they are clear and as easy to understand as possible, so if I were answering, I may include what you put in yours after first saying 'No, it is not possible to have mulitple outputs when using coder.ceval: it can only return a single, scalar output.' As it stands, I would not regard your post as having answered my question.
@weirdgyn I'm not assuming, I'm guessing. You didn't say why you needed the directory. I also said "Don’t write to the directory where the binary is" and "Most applications store user data in a fixed directory off of the home directory". I don't know who or what deploys data to that directory, but that should be changed IMO.
I am connecting CCS6.2 to Matlab2023b, but I'm getting an error when I use code "ticcs('boardnum',0, 'procnum', 0)" to identify F2812 board. I used it by Matlab2011, and I didn't have any problems. Can anyone help me, please? I want to create a CCS object in the Matlab GUI host program so that I can control the start and stop of the DSP and the transmission of data after the model is automatically generated into code.
Apparently (i.e. according your experimentation !) an array cell containing a Matlab Object doesn't work (i.e. appears to be empty) when passed into Java, so saying it is "allowed" in the face of other evidence is a stretch. Either way, I think this is a pointless debate. (Feel free to report this as a Matlab bug if you want to.)
I'm experiencing a strange behaviour when using mfilename function. I compiled a script (myScript) that use mfilename into an executable and running it from a specific folder (C:\Users\username\Desktop\appfolder\). I tought mfilename returned the full path of the executable but this's not true... i.e. running myScript executable from the above folder and printing the value returned by mfilename I got: C:\Users\username\AppData\Local\Temp\username\mcrCache9.7\myScriptN\myScriptT\myScript Where myScriptN and myScriptT are temporary subfolders. Of course this path is totaly useless if you need to locate something that's local or relative to the binary folder. Is there a function that can return the correct path when the script is executed compiled. BTW the same issue is found also when script are compiled into DLL or .NET assemblies.
It's undocumented for Matlab to permit a logical input for the Z data in contour. See the matlab help for contour and contourc. Octave wrote its contourc to do input checking and throw an error for an incorrect input type, and that's what you're seeing. As an octave developer mentioned in your crosspost over at the Octave help forum, the best immediate path forward would be to recast all of the logical inputs coming from statements like cls==1 as type double, for example: contour(X, Y, double(cls==1),[1,1], 'r--'); This was previously captured in Octave bug #64078 which identified a long list of plot objects that limit or improperly handle certain input types. Not all of them are necessarily expected to be expanded, as Octave is generally hesitant to adopt undocumented behavior as that can (and has in the past) changed without notice causing further grief years down the road, but it can be considered on a case-by-case basis but at a minimum the known non-support of Matlab-undocumented behavior could be documented in Octave. This sort of compatibility seems fairly trivial, though, so it may improve in the future.
Consider moving the i loop to just wrap the if statement, you're doing loads of overwrites of the elements which are not dependent on i. Then it also becomes more obvious where to put your assignments for form(x,y,z).c_top, you can just do it after the i loop for each struct c for j=1:length(Cr) for m=1:length(TR) for k=1:length(pH) form(j,m,k).name = ["c" num2str(Cr(j)) "TR" num2str(TR(m)) "ph" num2str(pH(k))]; form(j,m,k).Cr = Cr(j); form(j,m,k).Ct = Cr(j)*TR(m); % corde tip form(j,m,k).S = (form(j,m,k).Cr+form(j,m,k).Ct)*H/2; form(j,m,k).AR = H^2./form(j,m,k).S; for i = 1:N if (pH(k) == 0) form(j,m,k).c(i) = form(j,m,k).Ct*cos(phi(i))+form(j,m,k).Cr*(1-cos(phi(i))); elseif (yh(i) < H*pH(k)) form(j,m,k).c(i) = form(j,m,k).Cr; else form(j,m,k).c(i) = form(j,m,k).Cr+(form(j,m,k).Ct-form(j,m,k).Cr)/(H-pH(k)*H)*(yh(i)-pH(k)*H); end end form(j,m,k).c_top = form(j,m,k).c(N/2+1:end); form(j,m,k).c_bot = form(j,m,k).c(1:N/2); end end end
Using pwd instead of mfilename fixes everything.
@n.m.couldbeanAI so far I cannot find a way to specify such option in the command line (that's generated by mbuild)
Trouble with From Spreadsheet Block in Simulink
Arrays can be both inputs and outputs as pointers, the limitation is having datatypes that are arrays, like "typedef double doublearray[50]". If a function uses the doublearray type in it's prototype, you need to write a wrapper.
Matrix Multiplication Error in MATLAB R2022 but Not in R2024 (ECEF-to-ECI Transformation)
@beaker was hinting at that you need to preallocate the array. You are increasing the size of the array with every iteration, this takes a lot of time. Read here: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html -- If you use the MATLAB editor, it should have put a red wriggly line under the assignment into `a`, and when you hover over it, it shows you the warning.
Note that you need a function handle to minimise, but that doesn't mean you have to define everything in anonymous functions. It might be easier to test and debug if you just write a complete function block, so you have your main function g which evaluates some variable-sized v using a predefined f: function x = g( f, v ) % v is an array of unknown size, the values of which should be % passed as separate inputs to f % Convert to cell so we can use {:} syntax in function call vc = num2cell( v ); % Evaluate x = f( v{:} ); end Then all your anonymous function needs to do is wrap this up so that it accepts a single input gf = @(s) g( f, y + s*e_i ) [lambda,~] = fminsearch( gf, 0 ) Alternatively if you'd written the definition of f directly within the function block for g then you wouldn't need to define gf at all, you could point directly at g if it took a single input. If you have these in the same script, you would normally put the function block at the bottom (although since R2024b they can go anywhere)
Side-note on MATLAB: `tic/toc` is not recommended for accurate timings for a multitude of reasons. Use [`timeit()`](https://www.mathworks.com/help/matlab/ref/timeit.html) instead. This circumvents several problems, mainly the start-up time of the engine and averaging out differences in run time between runs.
The issue is that if you want to copy and paste a curve, the best way is to manually extract the original data and then redraw it using yyaxis right in a new plot or in the same plot, instead of directly copying and pasting！ You should provide some data and code to clarify your meaning. In the absence of that, let’s assume I am using the data and code below to illustrate your point, which might not be accurate, so please point it out. %% Generate sample data (Permeability &amp; Impedance) % Assume permeability (left axis) and impedance (right axis) vary over time x1 = 0:0.1:10; % Time axis (permeability) y1 = 10*sin(x1) + x1; % Permeability data (sine wave with linear growth) x2 = 0:0.1:10; % Time axis (impedance) y2 = 5*cos(x2) + 2*x2; % Impedance data (cosine wave with linear growth) %% Step 1: Plot the original graph (left axis: permeability, right axis: impedance) figure(1); clf; % Left axis: Permeability yyaxis left; h_permeability = plot(x1, y1, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Permeability'); ylabel('Permeability (Unit)'); ylim([min(y1)-5, max(y1)+5]); % Right axis: Impedance yyaxis right; h_impedance = plot(x2, y2, 'r--', 'LineWidth', 1.5, 'DisplayName', 'Impedance'); ylabel('Impedance (Ω)'); ylim([min(y2)-5, max(y2)+5]); % Add title and legend title('Original Data: Permeability vs. Impedance'); legend('Location', 'northwest'); grid on; %% Step 2: Extract data and generate a comparison graph (copy curves to the same axis) figure(2); clf; % Left axis: Plot two permeability curves yyaxis left; hold on; plot(x1, y1, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Permeability 1'); plot(x1, y1 + 8, 'b:', 'LineWidth', 1.5, 'DisplayName', 'Permeability 2 (Shifted)'); % Copy and shift ylabel('Permeability (Unit)'); ylim([min(y1)-5, max(y1)+15]); % Adjust range to accommodate the new curve % Right axis: Plot two impedance curves yyaxis right; hold on; plot(x2, y2, 'r--', 'LineWidth', 1.5, 'DisplayName', 'Impedance 1'); plot(x2, y2 * 0.6, 'r-.', 'LineWidth', 1.5, 'DisplayName', 'Impedance 2 (Scaled)'); % Copy and scale ylabel('Impedance (Ω)'); ylim([min(y2)-5, max(y2)+5]); % Add title, legend, and grid title('Comparison: Two Permeability &amp; Two Impedance Curves'); legend('Location', 'northwest'); grid on;
I wrote the Matlab GUI script below in App Designer in order to select an image ROI: function markROIButtonPushed(app, event) function allevents(src,evt) evname = evt.EventName; switch(evname) case{'MovingROI'} disp(['ROI moving previous position: ' mat2str(evt.PreviousPosition)]); disp(['ROI moving current position: ' mat2str(evt.CurrentPosition)]); pos = roi.Position; app.col1 = floor(pos(1)); % Column 1 app.col2 = ceil(pos(1) + pos(3)); % Column 2 app.row1 = floor(pos(2)); % Row 1 app.row2 = ceil(pos(2) + pos(4)); % Row 2 app.x1Crop = app.col1; app.y1Crop = app.row1; case{'ROIMoved'} disp(['ROI moved previous position: ' mat2str(evt.PreviousPosition)]); disp(['ROI moved current position: ' mat2str(evt.CurrentPosition)]); pos = roi.Position; app.col1 = floor(pos(1)); % Column 1 app.col2 = ceil(pos(1) + pos(3)); % Column 2 app.row1 = floor(pos(2)); % Row 1 app.row2 = ceil(pos(2) + pos(4)); % Row 2 app.x1Crop = app.col1; app.y1Crop = app.row1; end end imshow(app.I,'Parent', app.imageAxes); roi = drawrectangle(app.imageAxes); [app.Iy1,app.Ix1,app.Iz1] = size(app.I); addlistener(roi,'MovingROI',@allevents); addlistener(roi,'ROIMoved',@allevents); pos = roi.Position; app.col1 = floor(pos(1)); % Column 1 app.col2 = ceil(pos(1) + pos(3)); % Column 2 app.row1 = floor(pos(2)); % Row 1 app.row2 = ceil(pos(2) + pos(4)); % Row 2 app.x1Crop = app.col1; app.y1Crop = app.row1; if app.col1 < 1 app.col1 = 1; end if app.row1 < 1 app.row1 = 1; end if app.col2 > app.Ix1 app.col2 = app.Ix1; end if app.row2 > app.Iy1 app.row2 = app.Iy1; end end % Button pushed function: selectROIButton function selectROIButtonPushed(app, event) app.Icrop = app.I(app.row1 : app.row2, app.col1 : app.col2, :) disp(app.col1) disp(app.row1) app.RoiOn = true; app.ROISwitch.Enable = 'off'; end But when I wish to start to mark the ROI from the image coordinates (1,1) for the upper-left corner of the image I get this error “Index in position 2 is invalid. Array indices must be positive integers or logical values.” The same issue will appear in the lower-left corner of the image (error: "Index in position 1 exceeds array bounds. Index must not exceed...")? How can I solve it?
Your first snippet is known to be slow and hence gives a warning. Preallocate arrays if you can. The second is indeed preallocated, I doubt that can be sped-up by much. You might want to [edit] your post to a more concrete example, as this seems too much reduced. Adding the same data to multiple pages of a matrix isn't very relevant. Do you want to concatenate matrix `A` n times, or various matrices with different names? In case of the former: do explain *why* you need to do this, as this sound like an [XY problem](https://meta.stackexchange.com/q/66377/325771).
What you describe used to be done via either `arrayfun` or `bsxfun`. Nowadays, implicit expansion might be able to take care of multidimensional arrays, though you'd need to check that. (In the sense that given an M x N x L matrix `A` and M x N matrix `B`, `A-B` might give you a result these days and even the correct one at that. Might need to `permute()` your way around to shift dimensions to their proper positions beforehand.)
Thermoteknix MicroCAM 3. It's not going to help the driver is what it is, and I am looking for a Matlab work around.
I would keep the row name as a column rather than an actual row name property of the table, and then you want to stack the data (make it a tall, "stacked" table) rather than unstack it (to make it wider). You can do something like this: Set up the example table slightly differently: row_names = {'row1','row2','row3'}; col_names = {'col1','col2','col3','col4','col5'}; table_values = [0.2, 0, 0, 0.3, 0; 0, 0.2, 0.2, 0, 0.1; 0.5, 0.5, 0, 0, 0]; tbl = table(); tbl.RowName = categorical(row_names.'); tbl_data = array2table(table_values, 'VariableNames', col_names); tbl = [tbl, tbl_data]; Then stack it, naming the two new columns which will be generated stacked = stack(tbl, col_names, 'NewDataVariableName', 'Value', 'IndexVariableName', 'ColName' ); Then it should be trivial to filter on the Value column: filt = stacked( stacked.Value ~= 0, : ); filt = 7×3 table RowName ColName Value _______ _______ _____ row1 col1 0.2 row1 col4 0.3 row2 col2 0.2 row2 col3 0.2 row2 col5 0.1 row3 col1 0.5 row3 col2 0.5 This would still work if you were using the RowNames property of the table, but they will get a numerical suffix to make them unique after the stacking, which isn't really what you want.
Thank you! I tried using ICP, but the two clouds do not overlap, and the registration is not satisfactory. Do you know how I can improve it?prove it? I added the code to the question.
I want to apply constrained ordinary least-squares regression similar to what is done with R here, but in Matlab. The documentation doesn't suggest how to accomplish this with the available routine fitlm (running version R2023A with the statistics and ML toolbox). Using Wilkinson notation the model y ~ 1+x1+x2 would be fit to response column variable y with column covariates x1 and x2 as tbl=table(x1,x2,y); m0=fitlm(tbl, 'y~1+x1+x2'); It seems simple enough to treat x2 as a covariate while holding x1 fixed at some value, just subtract x1*beta1 from y: yp = y- x1*beta1; % beta1 is constant tbl=table(x2,yp); m1=fitlm(tbl, 'yp~1+x2'); However there is an uncertainty associated with beta1 which needs to be propagated into beta2, which the above doesn't accomplish. It also feels clumsy and possibly reinvents the wheel. (1) Are there openly available utilities to do this in Matlab? (2) If not, how to perform a constrained fit ensuring the uncertainty in beta1 is propagated into the other coefficient? Input would be y,x1,x2, beta1 and sbeta1 (standard error of beta1). Desired output is beta2 and sbeta2 plus other statistical output generated by the regression (eg standard error).
I am using a 14bit thermal camera, but it advertises itself as YUYV. I know this is not the format the camera is using and I can decode and convert this data to the 14bit gray scale if I have the data. Matlab captures the image and then "converts" it to RGB or YUV to get nonsense data. I know the camera format is the root cause but I need a way round this, Is there a way to get the camera raw data in Matlab (without it being converted to YUV or RGB)? Or is there a way to tell Matlab to ignore the format and see it as 16bit gray (could even live with 8bit gray if all the data was there). There is little chance of the camera manufacture changing the advertised format to gray 16. (I have all the image add-ons if required) Exploded all doc's and add-ons, nothing there.
Jonathan thanks for practising the art of double checking and careful reading. I have corrected the input index in the support function to turn points to coefficients. Regarding the -d the formula comes from Wiky and the -d is used in several lines so I am going to keep both options in my answer, for the question originator to have both and perhaps verify whether Wiky formula is correct or not. Thanks
MinGW-W64 undefined reference to `WinMain' compiling DLL
For positive arrays min is probably the fastest solution: x = sparse(5000, 1); x(randsample(5000, 500)) = 1; [~, idx] = min(x); ismember can also be used: [~, ind] = ismember(0, x);
If you want to break out of the for loop early then you should use break Flag = 0; while Flag == 0 for x = 1:10 if x == 3 Flag = 1; break % Exit the 'for' loop end end end
it should be easy with Matlab 1) First import xml using https://www.mathworks.com/help/matlab/import_export/importing-xml-documents.html 2) Then export to stl using https://www.mathworks.com/matlabcentral/answers/284479-how-to-export-3d-data-from-matlab-as-a-stl-or-obj-file
@Adriaan Thank you for the comments, I've corrected the *minimum*. I have tried the direct approach with matrices and it works both for `-` and `.*` I haven't found this functionality in the documentation...
*"Data conversion between java and matlab buggy?"* - Given how mature MATLAB is, I seriously doubt it. More likely, it doesn't work the way you think it works ... and its not a bug.
I'm trying to solve a MILP problem in Matlab Optimization Toolbox. I'm encountering with problems with the product of two decision variable of my problem which are bounded. 0&lt;= x &lt;= 60 0 &lt;= y &lt;= 8760 The product is inside the objective function that is minimization of the cost. For this reason when I tried with the method http://www.aimms.com/aimms/download/manuals/aimms3om_integerprogrammingtricks.pdf explained here, I obtained a value always equal to zero, that is not what I want. I'd like to a value in time that is equal to the product x*y. The variable x is a non linear function of time which represents a power, while y is the cumulative sum of the working hours of operation of the system, that goes from 0, if the system is not working, to 8760 if the system work every hour. clear all close all clc addpath('C:\gurobi1103\win64\examples\matlab') %% Input data % Define the main path manually, e.g. 'C:\Users\My_models' path_main = 'C:\Users\nanf\Desktop\H2-districts'; % path for input files path_input = fullfile(path_main, 'Input'); % Define the path for functions path_functions = fullfile(path_main, 'Functions'); % Reading an Excel file from the Input directory excelFilePath1 = fullfile(path_input, 'Inputs_BoundaryLoads_2022.xlsx'); excelFilePath2 = fullfile(path_input, 'nestel_demand.csv'); excelFilePath3 = fullfile(path_input, 'PriceImpExp_ele.xlsx'); Input1 = readtable(excelFilePath1); Input2 = readtable(excelFilePath2); Input3 = readtable(excelFilePath3); %% Pre-processing nHours = 8760; % Number of hours simulated [8760h] irradiance = Input1.G; % Hourly solar irradiance [W/m^2] idxHr2ToEnd = (2:nHours)'; % Hours until the end Time = (1:nHours)'; % Time vector days = nHours/24; % Number of days simulated weeks = days/7; % Number of weeks simulated clear t; linew = 1.5; font = 18; %% INPUT PARAMETERS % general inputs bigM = 1e8; % Large number for big-M constraints MaxSimTime = 900; % Maximum time for MILP solver [s] deltat = 3600; % time step di 1h [s] % Electrical district demand P_load = Input2.P_el_nest_h; % NEST electrical demand [kW] % Fixed technical parameters HHV = 39.39 * 3.6 * 10^3; % Hydrogen higher heating value [kJ/kg] % Costs and Efficencies c_h2 = 2; % cost of hydrogen [CHF/kg] c_gridimp = Input3.Priceimpgreen; % [CHF/kWh] c_gridexp = Input3.PriceexpPV; % [CHF/kWh] eff_b = 0.95; % constant efficiency of the battery (round trip efficency) eff_PV = 0.17; % constant efficiency of the PV system eff_FC = 0.50; % Nominal electrical efficency of FC % Lifetime in hours for PEMFC from Technology RoadMap-Hyydrogen and Fuel Cells,IEA(2015) nH_lifetime = 40000; % [h] % PEM fuel cell lifetime was defined by the time elapsed until 10% of the initial voltage/performance is lost Delta_eff_FC = 0.1*eff_FC; % [-] % Fuel Cell degradation rate as a constant value in Nani-Model Const1 = Delta_eff_FC/nH_lifetime; % [1/h] % further constant for MILP model from Taylor expansion Const3 = Const1/HHV/eff_FC^2; %[kg/h/kJ] % Const2 = Const3*P_FC_opt; % Fuel Cell (FC) S_FC_min = 0; % Minimum size FC [kW] S_FC_max = 60; % Maximum size FC [kW] % PV P_PV_peak_ref = 100; % Reference value peak power PV [kW] Area_PV_ref = P_PV_peak_ref/eff_PV; % Reference area PV [m2] Area_PV_min = 0; % Minimum area PV [m2] Area_PV_max = Area_PV_ref*2; % Maximum area PV [m2] % Battery C_b_max = 96 * 3.6 * 10^3; % Battery capacity [kJ] C_b_min = C_b_max / 3; % MIN Battery capacity [kJ] P_b_max = C_b_max / 3600; % Battery capacity (1C rate) [kWh] % unit prices and lifetime components d = 0.05;%0.04; % Discount rate ann = d / (1 - (1 + d)^(-20)); % annuity factor calculated with plant lifetime UP_PV = 1300;%1240; % Unit price PV [CHF/kW_p] life_PV = 25;%30; % Lifetime PV [years] maint_PV = 0.01;%0.0158; % Annual cost maintenance PV, frac total cost ann_PV = d / (1 - (1 + d)^(-life_PV)); UP_b = 1000;%600 % Unit price battery [CHF/kWh] life_b = 12;%10; % Lifetime battery [years] maint_b = 0.02; % frac capex ann_b = d / (1 - (1 + d)^(-life_b)); UP_FC = 950;%3000 % Unit price FC [CHF/kW] life_FC = 7.5;%15 % Lifetime FC [years] maint_FC = 0.024;%0.02 % Annual cost maintenance FC, frac capex cost ann_FC = d / (1 - (1 + d)^(-life_FC)); aux_maxs = (S_FC_max+nHours); aux_mins = 0; aux_maxd = S_FC_max; aux_mind = -nHours; %% PWL run PWL_productcontvariables.m %% Define the optimization problem and the optimization variables sizingprob = optimproblem; %% DECISION VARIABLES % SIZING decision variables % Battery capacity in [kJ] C_b = optimvar('C_b','LowerBound',C_b_min,'UpperBound',C_b_max); % C_b actual installed capacity,C_b_max= max capacity we can have % Fuel Cell size in [kW] S_FC = optimvar('S_FC','LowerBound',S_FC_min,'UpperBound',S_FC_max); % PV area in [m2] Area_PV = optimvar('Area_PV','LowerBound',Area_PV_min,'UpperBound',Area_PV_max); % OPERATIONAL decision variables % fuel cell generated power in [kW] P_FC = optimvar('P_FC',nHours,'LowerBound',0,'UpperBound',S_FC_max); % additional variables for FC operation implementation P_FC_On = optimvar('P_FC_On',nHours,'LowerBound',0,'UpperBound',S_FC_max); delta_On = optimvar('FC_On',nHours,'Type','integer','LowerBound',0,'UpperBound',1); % Degradation auxiliary variable [h] w_hours = optimvar('w_hours',nHours,'LowerBound',0,'UpperBound',nHours); %cumulative summation of FC_On % mass flow rate of H2 [kg/h] m_flow_H2 = optimvar('m_flow_H2',nHours,'LowerBound',0,'UpperBound',S_FC_max/eff_FC/HHV.*3600*3); % imported power from the grid in [kW] P_imp = optimvar('P_imp',nHours,'LowerBound',0); % exported power to the grid in [kW] P_exp = optimvar('P_exp',nHours,'LowerBound',0); % Battery energy content in [kWh] E_b = optimvar('E_b',nHours,'LowerBound',0,'UpperBound',C_b_max); % Battery charging power in [kW] P_b_ch = optimvar('P_b_ch',nHours,'LowerBound',0,'UpperBound',P_b_max); % Battery discharging power in [kW] P_b_disch = optimvar('P_b_disch',nHours,'LowerBound',0,'UpperBound',P_b_max); %% Additional Decision Variables for PWA Approximation % Squared variables for X and Y square_X = optimvar('square_X', nHours,'LowerBound', 0,'UpperBound',(nHours+S_FC_max)^2*2); % f(t)=x^2, x=(P_fc+w_hours)^2 square_Y = optimvar('square_Y', nHours, 'LowerBound', 0, 'UpperBound',(nHours+S_FC_max)^2*2); % f(t)=y^2, y=(P_fc-w_hours)^2 X_var = optimvar ('X_var',nHours, 'LowerBound',aux_mins,'UpperBound',aux_maxs); Y_var = optimvar ('Y_var',nHours,'LowerBound',aux_mind,'UpperBound',aux_maxd); delta_sum1 = optimvar('delta_sum1','Type','integer','LowerBound',0,'UpperBound',1); delta_sum2 = optimvar('delta_sum2','Type','integer','LowerBound',0,'UpperBound',1); delta_sum3 = optimvar('delta_sum3','Type','integer','LowerBound',0,'UpperBound',1); delta_sum4 = optimvar('delta_sum4','Type','integer','LowerBound',0,'UpperBound',1); aux_sum1 = optimvar('aux_sum1','LowerBound',aux_mins,'UpperBound',aux_maxs); aux_sum2 = optimvar('aux_sum2','LowerBound',aux_mins,'UpperBound',aux_maxs); aux_sum3 = optimvar('aux_sum3','LowerBound',aux_mins,'UpperBound',aux_maxs); aux_sum4 = optimvar('aux_sum4','LowerBound',aux_mins,'UpperBound',aux_maxs); delta_diff1 = optimvar('delta_diff1','Type','integer','LowerBound',0,'UpperBound',1); delta_diff2 = optimvar('delta_diff2','Type','integer','LowerBound',0,'UpperBound',1); delta_diff3 = optimvar('delta_diff3','Type','integer','LowerBound',0,'UpperBound',1); delta_diff4 = optimvar('delta_diff4','Type','integer','LowerBound',0,'UpperBound',1); aux_diff1 = optimvar('aux_diff1','LowerBound',aux_mind,'UpperBound',aux_maxd); aux_diff2 = optimvar('aux_diff2','LowerBound',aux_mind,'UpperBound',aux_maxd); aux_diff3 = optimvar('aux_diff3','LowerBound',aux_mind,'UpperBound',aux_maxd); aux_diff4 = optimvar('aux_diff4','LowerBound',aux_mind,'UpperBound',aux_maxd); % Reformulated product term PFC_w_hours = optimvar('PFC_w_hours', nHours, 'LowerBound', 0, 'UpperBound', S_FC_max*nHours); %% Derived variables % PV generated power P_PV = irradiance.*eff_PV*Area_PV/1000; % [kW] P_PV_peak = 1000*eff_PV*Area_PV/1000; % [kW] % C-rate of battery [kWh] P_b_lim = C_b / 3600; % new max capacity in [kWh] %% CONSTRAINTS % energy balance sizingprob.Constraints.EnBalance = (P_FC + P_PV + P_b_disch + P_imp) == (P_b_ch + P_load + P_exp); % BATTERY % sizingprob.Constraints.NoSimultaneousChDisch = discharging_on + charging_on &lt;= ones(nHours,1); sizingprob.Constraints.PowerBatt_ch_0 = P_b_ch(1) == 0; sizingprob.Constraints.PowerBatt_disch_0 = P_b_disch(1) == 0; %sizingprob.Constraints.Ch_on1 = P_b_ch &lt;= P_b_max * charging_on; sizingprob.Constraints.Ch_on2 = P_b_ch &lt;= P_b_lim; %sizingprob.Constraints.Disch_on1 = P_b_disch &lt;= P_b_max * discharging_on; sizingprob.Constraints.Disch_on2 = P_b_disch &lt;= P_b_lim; sizingprob.Constraints.E_b_update = E_b(idxHr2ToEnd) - E_b(idxHr2ToEnd-1) == P_b_ch(idxHr2ToEnd)*deltat - P_b_disch(idxHr2ToEnd)*deltat; sizingprob.Constraints.E_b_cont = E_b(1) == E_b(end); sizingprob.Constraints.E_b_max = E_b &lt;= C_b; % sizingprob.Constraints.E_b_min = E_b &gt;= 0.2 * C_b; % FC sizingprob.Constraints.MaxPowerFC = P_FC &lt;= P_FC_On; % sizingprob.Constraints.MinPowerFC = P_FC &gt;= 0.2 * P_FC_On; sizingprob.Constraints.PowerFC1 = P_FC_On &lt;= S_FC_max * delta_On; sizingprob.Constraints.PowerFC2 = P_FC_On &lt;= S_FC; sizingprob.Constraints.PowerFC3 = P_FC_On &gt;= S_FC - S_FC_max.*(ones(nHours,1) - delta_On); sizingprob.Constraints.PowerFC4 = P_FC &lt;= S_FC_max * delta_On; % Constraints for cumulative summation sizingprob.Constraints.SumCum_0 = w_hours(1) == delta_On(1); sizingprob.Constraints.SumCum_update = w_hours(idxHr2ToEnd) == w_hours(idxHr2ToEnd-1) + delta_On(idxHr2ToEnd); sizingprob.Constraints.pwl_segmentactsum = delta_sum1+delta_sum2+delta_sum3+delta_sum4==1 ; sizingprob.Constraints.pwl_segmentactdiff = delta_diff1+delta_diff2+delta_diff3+delta_diff4==1 ; %% (Pfc+whours)^2 % for auxiliary variable sizingprob.Constraints.auxsum11 = aux_sum1 &lt;= aux_maxs*delta_sum1; sizingprob.Constraints.auxsum12 = aux_sum1 &gt;= aux_mins*delta_sum1; sizingprob.Constraints.auxsum13 = aux_sum1 &lt;= X_var; sizingprob.Constraints.auxsum14 = aux_sum1 &gt;= X_var - aux_maxs *(1-delta_sum1); sizingprob.Constraints.auxsum21 = aux_sum2 &lt;= aux_maxs*delta_sum2; sizingprob.Constraints.auxsum22 = aux_sum2 &gt;= aux_mins*delta_sum2; sizingprob.Constraints.auxsum23 = aux_sum2 &lt;= X_var; sizingprob.Constraints.auxsum24 = aux_sum2 &gt;= X_var - aux_maxs *(1-delta_sum2); sizingprob.Constraints.auxsum31 = aux_sum3 &lt;= aux_maxs*delta_sum3; sizingprob.Constraints.auxsum32 = aux_sum3 &gt;= aux_mins*delta_sum3; sizingprob.Constraints.auxsum33 = aux_sum3 &lt;= X_var; sizingprob.Constraints.auxsum34 = aux_sum3 &gt;= X_var - aux_maxs *(1-delta_sum3); sizingprob.Constraints.auxsum41 = aux_sum4 &lt;= aux_maxs*delta_sum4; sizingprob.Constraints.auxsum42 = aux_sum4 &gt;= aux_mins*delta_sum4; sizingprob.Constraints.auxsum43 = aux_sum4 &lt;= X_var; sizingprob.Constraints.auxsum44 = aux_sum4 &gt;= X_var - aux_maxs *(1-delta_sum4); % sizingprob.Constraints.z_plus_lb_seg1 = X_var &gt;= xxs(1) * delta_sum1; sizingprob.Constraints.z_plus_ub_seg1 = X_var &lt;= xxs(2) * delta_sum1 + xxs(3) * delta_sum2 + xxs(4)*delta_sum3+xxs(5)*delta_sum4; % sizingprob.Constraints.z_plus_lb_seg2 = X_var &gt;= xxs(2) * delta_sum2; % sizingprob.Constraints.z_plus_ub_seg2 = X_var &lt;= xxs(3) * delta_sum2; % sizingprob.Constraints.z_plus_lb_seg3 = X_var &gt;= xx(3) * delta_sum3; % sizingprob.Constraints.z_plus_ub_seg3 = X_var &lt;= xx(4) * delta_sum3; % sizingprob.Constraints.z_plus_lb_seg4 = X_var &gt;= xx(4) * delta_sum4; % sizingprob.Constraints.z_plus_ub_seg4 = X_var &lt;= xx(5) * delta_sum4; sizingprob.Constraints.V_PWA_X = square_X == aas(1)* aux_sum1 + bbs(1) * delta_sum1 + aas(2) * aux_sum2 + bbs(2)* delta_sum2 +aas(3) * aux_sum3 + bbs(3)* delta_sum3 + aas(4) * aux_sum4 + bbs(4)* delta_sum4; %% DIFF % for auxiliary variable sizingprob.Constraints.auxdiff11 = aux_diff1 &lt;= aux_maxd*delta_diff1; sizingprob.Constraints.auxdiff12 = aux_diff1 &gt;= aux_mind*delta_diff1; sizingprob.Constraints.auxdiff13 = aux_diff1 &lt;= Y_var; sizingprob.Constraints.auxdiff14 = aux_diff1 &gt;= Y_var - aux_maxd *(1-delta_diff1); sizingprob.Constraints.auxdiff21 = aux_diff2 &lt;= aux_maxd*delta_diff2; sizingprob.Constraints.auxdiff22 = aux_diff2 &gt;= aux_mind*delta_diff2; sizingprob.Constraints.auxdiff23 = aux_diff2 &lt;= Y_var; sizingprob.Constraints.auxdiff24 = aux_diff2 &gt;= Y_var - aux_maxd *(1-delta_diff2); sizingprob.Constraints.auxdiff31 = aux_diff3 &lt;= aux_maxd*delta_diff3; sizingprob.Constraints.auxdiff32 = aux_diff3 &gt;= aux_mind*delta_diff3; sizingprob.Constraints.auxdiff33 = aux_diff3 &lt;= Y_var; sizingprob.Constraints.auxdiff34 = aux_diff3 &gt;= Y_var - aux_maxd *(1-delta_diff3); sizingprob.Constraints.auxdiff41 = aux_diff4 &lt;= aux_maxd*delta_diff4; sizingprob.Constraints.auxdiff42 = aux_diff4 &gt;= aux_mind*delta_diff4; sizingprob.Constraints.auxdiff43 = aux_diff4 &lt;= Y_var; sizingprob.Constraints.auxdiff44 = aux_diff4 &gt;= Y_var - aux_maxd *(1-delta_diff4); % sizingprob.Constraints.z_minus_lb_seg1 = Y_var &gt;= xxd(1) * delta_diff1; sizingprob.Constraints.z_minus_ub_seg1 = Y_var &lt;= xxd(2) * delta_diff1+xxd(3) * delta_diff2+xxd(4)*delta_diff3+xxd(5)*delta_diff4; % sizingprob.Constraints.z_minus_lb_seg2 = Y_var &gt;= xxd(2) * delta_diff2; % sizingprob.Constraints.z_minus_ub_seg2 = Y_var &lt;= xxd(3) * delta_diff2; % sizingprob.Constraints.z_minus_lb_seg3 = Y_var &gt;= xx(3) * delta_diff3; % sizingprob.Constraints.z_minus_ub_seg3 = Y_var &lt;= xx(4) * delta_diff3; % sizingprob.Constraints.z_minus_lb_seg4 = Y_var &gt;= xx(4) * delta_diff4; % sizingprob.Constraints.z_minus_ub_seg4 = Y_var &lt;= xx(5) * delta_diff4; sizingprob.Constraints.V_PWA_Y = square_Y == aad(1) * aux_diff1 + bbd(1) * delta_diff1 + aad(2) * aux_diff2 + bbd(2) * delta_diff2 + aad(3) * aux_diff3 + bbd(3) * delta_diff3 + aad(4) * aux_diff4 + bbd(4)* delta_diff4; % Reformulated product constraint using both PWA functions sizingprob.Constraints.ProductApprox1 = PFC_w_hours == (1/4) * (square_X - square_Y); sizingprob.Constraints.ProductApprox2 = PFC_w_hours &lt;=nHours*S_FC_max; sizingprob.Constraints.ProductApprox3 = PFC_w_hours &gt;=0; % mass flow rate calculation sizingprob.Constraints.massflowH2= m_flow_H2 == (P_FC./eff_FC./HHV).*3600 + PFC_w_hours*Const3*3600; % [kg/h] %% OBJECTIVE FUNCTION cost_inst = (P_PV_peak * UP_PV * ann_PV + S_FC * UP_FC * ann_FC + C_b/3600 * UP_b * ann_b)/1000; % [kEUR/y] cost_imp = sum(c_h2 * m_flow_H2) / 1000 + sum(P_imp .* c_gridimp) / 1000; % [kEUR/y] cost_exp = sum(P_exp .* c_gridexp) / 1000; % [kEUR/y] cost_maint = (maint_PV * P_PV_peak * UP_PV + maint_FC * S_FC * UP_FC + maint_b * UP_b * C_b/3600)/1000; % [kEUR/y] cost = cost_inst + cost_imp - cost_exp + cost_maint; % set objective sizingprob.Objective = cost; %% Solve optimization problem intcon = []; [solution,fval,reasonSolverStopped] = solve(sizingprob);
So, what I understand from the comments is that those lines are not parallel.
rahnema1's comment from proving ground: "You may try GraphBLAS that contains masked matrix multiplication operators." Yes, "masked matrix multiplication" sounds like what this is. Thanks for the recommendation
I asked ChatGPT, it told me "When you compile a Simulink model into a standalone executable (.exe) using Simulink Coder, the generated code is fixed at compilation time. The executable runs independently of MATLAB and does not support runtime parameter changes through MATLAB commands" Do you have other opinions or ideas to solve this problem? Thank you!
Suspicions I had that cascade of actions internally to matlab are likely as follow: Mouse is moved &gt; HitTest cache is reset &gt; Event WindowMouseMotion is fired &gt; HitTest cache is updated &gt; WindowButtonMotionFcn callback is called seems to be true, so I came out with following solution (here using UserData to store user-defined callback if any + keeping debug messages, just for demo purpose): function [] = TestFigEvents() %[ ... % Attach as an event addlistener(fig, 'WindowMouseMotion', @onMouseMove); %] end function [] = onMouseMove(s, e) %[ if (~iscell(s.UserData)) disp('Begin &gt;&gt; Event'); % Called by 'WindowMouseMotion' event % So just temporarely replace 'WindowButtonMotionFcn' s.UserData = { s.WindowButtonMotionFcn }; s.WindowButtonMotionFcn = @onMouseMove; % Not clear why but does not work if not performing this 'drawnow' drawnow; disp('End &lt;&lt; Event'); else disp('Begin &gt;&gt; Callback'); % Called by 'WindowButtonMotionFcn' callback % So do my stuff now that 'hittest' is ok disp('Begin &gt;&gt; My own stuff'); ht = hittest(s); disp(ht); disp('End &lt;&lt; My own stuff'); % Restore orginal 'WindowButtonMotionFcn' an call it if not empty s.WindowButtonMotionFcn = s.UserData{1}; s.UserData = []; if (~isempty(s.WindowButtonMotionFcn)), disp('Begin &gt;&gt; User defined stuff'); s.WindowButtonMotionFcn(s, e); disp('end &lt;&lt; User defined stuff'); end disp('End &lt;&lt; Callback'); end %] end NB1: So far it is unclear why I need to call drawnow but without it is not working (adding limitrate option just decrease precision for hittest detection, and nocallbacks make it not to work). NB2: Just doing a drawnow in initial event-listener does not work: function [] = onMouseMove(s, e) %[ drawnow(); % This only does not make hittest to work ht = hittest(s); disp(ht); %] end So I will go ahead with temporarely replacing WindowButtonMotionFcn callback if any (+ quite strange but mandatory drawnow).
Upon making that change, our answers were still giving different results! Unfortunately there is another bug I discovered in your `dist_point_plane` function. The final term in the numerator should be positive, so `...+d)/...`. Once this change was made, our answers are giving equivalent results.
Select an image ROI in Matlab app designer
As beaker said, this is just a display issue. The reason for that and ways to circumvent it are given in the linked duplicate.
Is this a USB camera? If the camera does not advertise a grayscale format, then there is no way on earth to ask it to produce that. What is the camera make and model? We can check the USB descriptors to see what it actually offers.
Add these lines after your existing code: [x1Grid,x2Grid] = meshgrid(linspace(min(X(:,1)), max(X(:,1)), 100), ... linspace(min(X(:,2)), max(X(:,2)), 100)); [~,scores] = predict(SVMModel, [x1Grid(:), x2Grid(:)]); scores = reshape(scores, [size(x1Grid,1), size(x1Grid,2), 3]); % add color to each region [pred,~] = predict(SVMModel, [x1Grid(:), x2Grid(:)]); contourf(x1Grid, x2Grid, reshape(double(categorical(pred)), size(x1Grid)), 'LineStyle', 'none') contourcmap('jet', 'Colorbar', 'on') contour(x1Grid, x2Grid, scores(:,:,1) - max(scores(:,:,2:3),[],3), [0 0], 'k-'); contour(x1Grid, x2Grid, scores(:,:,2) - max(scores(:,:,[1 3]),[],3), [0 0], 'k--'); contour(x1Grid, x2Grid, scores(:,:,3) - max(scores(:,:,1:2),[],3), [0 0], 'k:'); The outcome is like:
I tried the following: I have a MATLAB class Value and want to push it onto a java stack like so stack = java.util.Stack a= Value % constructor of MATLAB class stack.push({a}) Note that I have to wrap a because passing MATLAB objects to java methods is not supported. Then I try to regain: a1 = stack.pop But here, a1 turns out to be array of type java.lang.Object[] but it is empty: a1 = java.lang.Object[] [[]] Can anyone tell me what went on and how to get what I want. To be honest, I will now just use matlab arrays to emulate the stack, but still... I am curious.
Problem: Use MATLAB's symbolic toolbox to find the general and particular solution for the transient response of i(t) in a simple/canonical RLC circuit. Challenge: Execution of the line iSol(t) = dsolve(eqn, [cond1, cond2]); in the code below raises an error that states that the solver is unable to reduce the square system because the number of equations differes from the number of indeterminates. Can someone help me resolve this issue? Code syms i(t) R L C V0 % Define component values R = 10; L = 1; C = 1; V0 = 12; % Define the differential equation eqn = L*diff(i(t), t, 2) + R*diff(i(t), t) + (1/C)*i(t) == 0; % Define initial conditions cond1 = i(0) == 0; % i(0) = 0 cond2 = diff(i(t),t) == V0/L; % di/dt(0) = V0/L % Solve the differential equation with initial conditions iSol(t) = dsolve(eqn, [cond1, cond2]); % Display the particular solution disp('Particular Solution for i(t):') disp(iSol(t))
Handle warning of "Array is wrong shape or size" when plotting a geopolyshape and setting the ColorData field in MATLAB
Why are my table columns not named properly?
What is this function `PreProcess`, where did you get it from? What is the problem with the code? Do you get any error messages? Please copy-paste them in full into your post.
@Irreducible How can I determine if my approach is correct based on the spectrum? I tried plotting the amplitude of the spectrum, but I don't know how to interpret the results.
You're right! Sorry! https://itpp.sourceforge.net/4.3.1/
Doesn't the last line of the table clearly say "Matlab Object: Not Suppoorted"? What is "obviously untrue" about that? (And if it is supported ... how come you can't find the Matlab documentation that explains how it should be done?
The camera is USB 640x480 and produces YUYV with the Y component holding the upper 8 bits and U / V components holding the lower 6 bits of a 14bit gray scale pixel. I am using windows for Matlab. The product I am working on is actually linux where I can use gstreamer to get the "YUYV" data and then have a custom plugin to convert to 14 or 8 gray. The camera is the problem it is incorrectly saying YUYV when it is not. I can do the conversion if I have the raw data.
I have two bodies in space composed by 3 points. A = [-50.0098 -181.0869 -37.5881]; B = [ -49.8410 -180.8097 -41.1383]; C = [-49.5887 -180.3952 -46.4462]; A = [-50.199 -180.93 -37.249]; B = [-50.256 -180.823 -33.686]; C = [-50.341 -180.657 -28.359]; I want to plot a plane through one of the 3D points and calculate the distance between the other point and this plane. Additionally, I want to plot it. I used the following function: %% ====== FUNCTION ====== function [normal, d, X, Y, Z] = plot_line_deviazione(p1, p2, p3, x_min, x_max, y_min, y_max) % This function plots a line from three points. % I/P arguments: % p1, p2, p3 eg, p1 = [x y z] % % % O/P is: % normal: it contains a,b,c coeff , normal = [a b c] % d : coeff normal = cross(p1 - p2, p1 - p3); d = p1(1)*normal(1) + p1(2)*normal(2) + p1(3)*normal(3); d = -d; x = x_min:x_max; y = y_min:y_max; [X,Y] = meshgrid(x,y); Z = (-d - (normal(1)*X) - (normal(2)*Y))/normal(3); mesh(X,Y,Z) In the following way: figure plot3(A(:,1),A(:,2),A(:,3),'r.','Markersize',25) hold on plot3(B(:,1),B(:,2),B(:,3),'r.','Markersize',25) plot3(C(:,1),C(:,2),C(:,3),'r.','Markersize',25) [normal0, d0, X0, Y0, Z0] = plot_line_deviazione(A, B, C, -100, 100, -100, 100); % new plane dot(X-d0,normal0) The "dot" would be the distance that I was looking for. Is this correct? How can I plo it? Thanks!
It would be interesting to know what you're trying to achieve with this, you could set variables to specific values when entering different scripts to trace whether you're in the second script, or at least make the sub mlx into a function file instead of using layered scripts, since this is typically more robust regardless whether those are "live" or "traditional" scripts
Thanks for the reply! It's worked perfect! How about adding color to each region in above figure? Can we do that too? Thanks in advance!
How can installed the preprocess library on matlab toolbox?
@jdweng stl is a file extension and is irrelevant to the tag [tag:stl]. Can you read the tag description one more time?
How do I hide the tick marks, but keep the tick labels on both y axis of a graph? My formatting for the axis is yyaxis left; b = bar(data(2:end-1,:)', "stacked"); xticklabels(data(1, :)); ax1 = gca; ax1.YGrid = "on"; ax1.YLim = [0, 1000]; ... yyaxis right; l = plot(data(end, :), 'k'); l.LineWidth = 2; ax2 = gca; ax2.YLim = [0,30]; box off; The result: The desired format:
chtz, pt 2: Essentially for that small binary matrix "L_block", each row of L_blockcorresponded to some submatrix of all 1s in C = ( A * B ) .* L. In the visual example I provided, L_block has 9 rows, thus there are 9 submatrices ("blocks") of 1s in L, each having their own row and column indices in L (and thus C), and I went over each of these submatrices (per each row in L_block) to evaluate that submatrix's entries in C.
I am working with fluorescence microscopy images of blood vessels in the brain, stored as HDF5 files (.h5). My goal is to extract vessel dimensions (diameters) from each frame in a time series and analyze how they change over time. Currently, I am using MATLAB to: Load the .h5 file and extract individual frames. Apply Gaussian filtering and contrast enhancement to improve vessel visibility. Perform edge detection (Canny) and skeletonization to extract vessel centerlines. Compute vessel diameters using the Euclidean distance transform from the skeleton. However, I am running into several issues: Edge detection is inconsistent and picks up artifacts inside the vessel. The skeleton sometimes extends beyond the vessels or is not continuous. Extracted diameters appear constant, even when the vessel visibly changes size. Working example of an h5 frame Current Approach in MATLAB Here’s the code I am using to manually select vessels and compute diameters: % Load a single frame from HDF5 file frame = double(h5read('file.h5', '/recording', [1,1,1,1000], [512,512,1,1])); % Preprocessing: Smoothing &amp; contrast enhancement frame = imgaussfilt(frame, 2); frame = imadjust(mat2gray(frame), stretchlim(mat2gray(frame), [0.01, 0.99])); % Edge detection &amp; binarization bw = imbinarize(frame, 'adaptive', 'Sensitivity', 0.5); bw = bwareaopen(bw, 50); % Skeletonization &amp; distance transform skeleton = bwskel(bw); distance_map = bwdist(~bw); diameter_map = distance_map * 2; % Extract diameters along the skeleton [y, x] = find(skeleton); diameters = arrayfun(@(i) diameter_map(y(i), x(i)), 1:length(x)); % Plot results figure; imshow(frame, []); hold on; scatter(x, y, 15, diameters, 'filled'); % Color vessels by width colormap(jet); colorbar; title('Vessel Skeleton &amp; Diameters'); % Diameter profile plot figure; plot(diameters, 'b.-'); xlabel('Skeleton Point Index'); ylabel('Vessel Diameter (pixels)'); title('Vessel Diameter Profile'); Resulting edges and vessel diameter detection As you can see, the edges are picked up but not always, and the diameters are calculated on no real basis. They don’t seem to be particularly telling. Question: How can I ensure accurate edge detection that captures the actual vessel boundaries and calculate their diameters?
The `WinMain` message is kind of bogus. Mingw looks for *either* `main` or `WinMain`, but only includes the latter in the message when none of them is found.
This extencion does not work great, every time I run a cell, it opens a new instance of matlab terminal. Maybe there are some problems with my settings
Also, you don’t need to loop in MATLAB: `R = image(:,:,1);`.
need to vectorize efficiently calculating only certain values in the matrix multiplication A * B, using a logical array L the size of A * B
Unrelated to the question, but you should use a perceptually uniform colormap. With the one you are using, a change from 0.1 to 0.2 is almost imperceptible, whereas from 0.6 to 0.7 it is very prominent
@weirdgyn I don’t think you can. In Windows, when you make an icon in the start menu or the desktop to launch an application, you can set the startup folder. This is the working directory at startup, and so will be what `pwd` returns. You don’t know that the CTF is in the working directory. But what you *can* do is avoid needing that directory name. Most applications store user data in a fixed directory off of the home directory. Don’t write to the directory where the binary is. Constant data should be inside the CTF.
You could try combining the matrices into a cell; `S = {A,B,C,...,N};` then using `cat` again: `out = cat(3,{:});` but I doubt this would be much faster. As for doing operations - check out the page operations [here](https://blogs.mathworks.com/loren/2021/01/14/paged-matrix-functions/), [here](https://blogs.mathworks.com/matlab/2024/05/29/paged-matrix-functions-in-matlab-2024-edition/), and [here](https://au.mathworks.com/help/parallel-computing/distributed.pagefun.html).
I drew two curves in a plot; permeability and impedance. And then tried to copy &amp; paste the same-type curves to compare 1:1. But the curve in yyaxis right is linked to yyaxis left, and I don't know how to link it to yyaxis right. I tried to change the y axis of the copied/pasted curve from left to right. I'd like to see/compare two permeability curves in yyaxis left and two impedance curves in yyaxis right.
`diff(i(t),t) == V0/L` does not say that the derivative is that value at t=0. It makes the derivative constant. But I don’t know how to do this right, I have very little experience with this toolbox.
If `L` is periodic, you could re-order `A` and `B` (thus implicitly also `L` and `C`) in a way that `C` has a block structure (and if necessary, afterwards re-re-order `C` to the desired order -- or better adapt the follow-up code to exploit the block-structure of `C`).
As an aside: The `Set-ExecutionPolicy Bypass -Scope Process -Force;` statement is unnecessary, given that you're merely invoking a .NET method, not a script file.
I am unable to get a transparent background in this MWE file; no errors. The procedure works fine for other types of Matlab plotting function fileName = 'C-13.tex'; % Input file name text = ' this this this a is a test'; text = lower(text); words = split(text); [uniqueWords, ~, idx] = unique(words); wordCounts = accumarray(idx, 1); wordTable = table(uniqueWords, wordCounts, 'VariableNames', {'Word', 'Frequency'}); wordTable = sortrows(wordTable, 'Frequency', 'descend'); topWordCount = 75; % Keep top 75 words wordTable = wordTable(1:min(topWordCount, height(wordTable)), :); hf = figure; wc = wordcloud(wordTable.Word, wordTable.Frequency); orangeColor = [1.0, 0.5, 0.0]; % Bright orange colorMap = repmat(orangeColor, numel(wc.WordData), 1); wc.Color = colorMap; %set(gca,'color', 'none'); set(gcf, 'color', 'None'); exportgraphics(hf,'out.pdf','BackgroundColor','none','ContentType','vector')
I understand, set_param is not used ot call executable but rather interact with the model parameters. Did you use the simulink parameter as i indicated? If so you cant pass a file, you need to pass a string with the parameter name and value as if it was a matlab command window command.
@Wolfie Would you mind turning your `repmat(1,1,...,n)` suggestion into an answer?
Please note that answers shouldn't be edited into the question. The correct way to deal with answers is to upvote those that helped you and accept the one that helped you most, see [What should I do when someone answers](/help/someone-answers). If you adapted rahnema1's answer so much, that it can be considered its own answer, please do add it as such. Link back to their original answer for attribution. [Answering your own question is allowed and even encouraged](/help/self-answer).
Configuring the decoding software to generate a monochrome image should give you an 8 bit monochrome result. Ignoring the u and v components.
`find(X==0,1)` compares the whole matrix to zero (maybe even producing a full matrix?), then looks for the first non-zero element. In the loop you don’t touch most of the matrix. And it being a sparse matrix, you likely have mostly zero elements (if not, don’t use a sparse matrix), so the loop should terminate really quickly. Note that `idx(n) = ii + (jj-1)*n` is the same as `idx(n) = kk`. And `x(ii,jj)==0` is the same as `x(kk)==0`. So removing the call to `ind2sub` should simplify and hopefully speed up your code.
If this a toy example or do you actually just want duplicates? If it's the later you can just use `repmat`. It's not clear to me what you mean by `MxNx...xn`, you want an n-dimensional array output? Because that's different to the 3-dimensional outputs in your examples.
I have a table that looks as follows: and I would like to get it into this format: in order to ultimately isolate all cells that have non-zero values: I need to be able to identify row name and column name for each value in the resulting table. Somehow I am having trouble finding the most efficient way to do this in Matlab. This is a sample script preparing all the data up to the point to where I would do the unstacking. row_names = {'row1','row2','row3'}; col_names = {'col1','col2','col3','col4','col5'}; table_values = [0.2, 0, 0, 0.3, 0; 0, 0.2, 0.2, 0, 0.1; 0.5, 0.5, 0, 0, 0]; table_source = array2table(table_values, 'RowNames', row_names, 'VariableNames', col_names); unstacked = unstack(table_source,col_names, col_names) would be happy to receive any suggestions how to do this. Thank you
You can't say "rounding doesn't work". Of course it does. However, there are different rounding policies. Matlab always rounds 0.5 up. Given your parameters, it is unlikely you are getting exactly 0.5. Have you manually converted the differing pixels to see where the differences happen? And, perhaps more important, why do you care? Why not just use the `rgb2gray` value?
Luis' solution is the same as fireflies'. There are minor differences (in that Luis uses a sparse matrix and then makes sure to put the outputs in the correct place) but the actual computations are done exactly the same way...so I'm not sure why there is such a difference between those two solutions.
Thanks Cris. What do you mean by 'looking through the data as stored'? You can of course use `find` to get the indexes of the non-zero elements -- but how would you then (quickly) find the first non-zero element? (without just looping through that list)
After rereading this, in addition to my comment above, how do you define "closest"? Is it (a form) of RMS? Your vector-scalar example appears to be wrong, as the largest *minimal* value would be picked, You'd need some form of `min(abs(S-a))`. Also note that you could use the second output of `min` rather than `find(A==min(A),1)`, as `[val, idx] = min(A)` gives you its index.
Do you get a warning in the MATLAB editor saying that the variable `a` appears to change size on every loop iteration? Also, why are you using `while` loops instead of, for example, `for y = 0:0.01:2*pi`?
How to read a CSV or Excel file of parameter names and values and assign them in MATLAB workspace
Oh, you could use `dot` instead of `sum(.*)`. Don’t know if it’s faster?
I'm inputting a simple excel spreadsheet into Simulink to pull data from. I checked the data in Simulink via a Scope Block and it does not match the output of the Excel data when plotted. I've attached screenshots of both. It appears that Simulink is using previous values and copying over other values with that data instead. Any ideas for why this is occurring and/or how to fix it will be appreciated.[enter image description here](https://i.sstatic.net/1w5CvH3L.png) I have tried adjusting the From Spreadsheet Block parameter inputs with no luck. I've checked the data in excel and it is okay. I've also reviewed the Simulink/Matlab page for the From Spreadsheet Block and can't find a reason for what is occurring.
Show only tick labels and hide tick marks: MATLAB 2024b
Would be great if you could add a [mcve] of what you're working with already
You may want to have a look here: https://or.stackexchange.com/questions/180/how-to-linearize-the-product-of-two-continuous-variables
I am writing a C MEX S-Function to perform some calculations on various datastores. Therefore, I would like to access the datastore values directly from within the S-function without explicitly specifying them as input ports. I tried the function mexGetVariablePtr, but could not find a way to get the value of a datastore during simulation.
I'm using the Holt-Winters model in MATLAB to forecast weather data. When I set the smoothing parameters (Alpha, Beta, and Gamma) too high, the model overfits the data and doesn't forecast well on new data. How can I adjust these parameters to avoid overfitting and improve the model's accuracy? I tried setting the smoothing parameters (Alpha, Beta, and Gamma) to higher values in my Holt-Winters model, expecting it to make the model more responsive to recent data. However, this caused the model to overfit the training data, leading to poor forecast accuracy when predicting new data. The model became too sensitive to past data, failing to generalize well to unseen data.
For the first question, it seems that I did not receive such warning. For the second question, I am more used to the `while` loop. It seems that this is not the key factor of the speed of the code.
The comments on your question ask about whether you see a warning in your editor about the array size increasing every loop, since that's what makes those lines slow. This is what they're referring to: You can work out up-front how big a is going to be and pre-allocate it. Using for loops makes this a bit clearer, so I've made both changes in the code below: Maxdeviation= ComputeDeviationSum(0,0,0,mufT, mufD, mufC); MaximizingArg= [0,0,0]; % Predefine sweep points X = 0:0.01:pi; Y = 0:0.01:2*pi; Z = 0:0.01:2*pi; i=1; % Pre-allocate output since we know how big it's going to be a = NaN(numel(X)*numel(Y)*numel(Z),4); % Loop over each point array for ix = 1:numel(X) x = X(ix); for iy = 1:numel(Y) y = Y(iy); for iz = 1:numel(Z) z = Z(iz); deviation= x+y+z; % Just an example. The function is more complex. if deviation&gt; Maxdeviation MaximizingArg= [x, y,z]; Maxdeviation= deviation; end % Assign output at this index to preallocated array a(i,:) = [x,y,z,deviation]; i = i+1; end end end Taking this further, it might be worth noting that storing x,y,z in the output array might be redundant, you could instead pre-allocate a=NaN(numel(X),numel(Y),numel(Z)) and then store the function value as a(ix,iy,iz)=deviation;. Then you can easily index into the resulting array for given indices of x, y and z. Conversely if you don't want to use the indices ix,iy,iz for anything you could simplify the loops to be something like for x = X and remove the assignments x = X(ix)
How to evaluate a MATLAB anonymous function that takes an arbitrary number of variables n, given a n-dimensional vector?
`repelem` now costs about 70% of time. I'll have a try on the parallel version of `repelem`. That's really nice and helpful
I'm relatively new to MATLAB so perhaps there's something I'm missing. The task is the following: we must program a certain algorithm for optimizing a continuous function f: Rn ---> R. The thing is, to do so I need to minimize a scalar function that depends on f, and work with said minimum, for example: %given f, and a vector y g=@(s) f(y + s*e_i) %e_i is the i-th canonical vector [lambda, ~]=fminsearch(g,0) disp(lambda) The problem is that, if for example f(x,y)=x+y, one can't input f([1,2]), you need to write f(1,2), so I don't know how to define the function g properly so I can find the needed scalar value. I know that if f were a fixed dimension, let's say 3, I could literally write eval_f = @(v) f(v(1), v(2), v(3)) g = @(s) eval_f(y + s*e_i) but the code must be open to receive any function. I have also tried using f(num2cell(y + s*e_i){:}) but I get an "Invalid array indexing" error, as I can't chain the parenthesis and an output. I have tried creating a more complex auxiliary function eval_f=@(fun,v) fun(feval(@(x) x{:},num2cell(v))); g=@(s) eval_f(f,y + s*ei); But doing feval(@(x) x{:},v) in the end only returns the first element of v, and f doesn't get evaluated correctly and thus g isn't correctly defined. How could I define g?
How to linearize the product of two continuous variables?
I have a matrix A and linearly independent vectors x_1,...,x_k, in the nullspace of A. I want to find x_{k+1}, ..., x_m such that x_1,...,x_k, x_{k+1}, ..., x_m is a basis of the null space of A. Is there a suitable Matlab command for this? Thank you
Error matlab : invalid dot name structure assignment because the structure array is empty
Thank you. Only mistake that I did was not to use combination of curly and simple brackets. It works for me. Cheers
I want to do point cloud registration between two files. One file is in STL format and the other one is in XML format. I have transformed the STL file in a point cloud. How can I transform the XML into an STL file so I can get the second point cloud? It has x y z points. reference_data = stlread('filename.stl'); reference_points = reference_data.Points; ptCloud = pointCloud(reference_points(:,:,:));
@Irreducible Yes, the results show that there is a linear shift in the phase spectrum and the magnitude is unchanged.
I'm trying to create a custom block in Simscape that convert energy from pressurized water into a torque. Here is my code: component pelton_turbine % Ce composant calcule le couple généré par l'eau sur la turbine. % Déclaration des ports nodes H = foundation.hydraulic.hydraulic; % Port hydraulique R = foundation.mechanical.rotational.rotational; % Port mécanique rotatif end % Déclaration des paramètres parameters eta = {0.85, '1'}; % Rendement de la turbine rho = {1000, 'kg/m^3'}; % Densité de l'eau r = {0.5, 'm'}; % Rayon moyen de la roue g = {9.81, 'm/s^2'}; % Gravité end % Déclaration des variables internes variables Q = {0, 'm^3/s'}; T = {0, 'N*m'}; % Couple généré H_head = {0, 'm'}; % Hauteur d'eau équivalente end branches % Débit hydraulique pris directement depuis le port H Q : H.q -&gt; *; end equations % Calcul de la hauteur d'eau (pression convertie en mètre de colonne d'eau) H_head == H.p/ (rho * g); % Calcul du couple généré par l'eau T == {eta * rho * Q * r * sqrt(H_head * 2 * g), 'N*m'}; % Transmission du couple à l’axe mécanique R.t == T; end end My problem is that I have this error when I try to build my component: Invalid use of a value with unit cm^3*kg/(m*s^2) when attempting to bind a unit. The value to which the unit is bound must not have an associated unit. • In pelton_turbine.pelton_turbine (line 36) eta = 0.8500 rho = {1000, 'kg/m^3'} Q = {[1x1 double], 'cm^3/s'} r = {0.5000, 'm'} H_head = {[1x1 double], 'm'} g = {9.8100, 'm/s^2'} I don't get why the flow rate (Q) is in cm^3/s instead of m^3/s and I don't know how to change it. Do you have an idea ? Since Q is a through variable I can't define his unit. I also tried changing the units in the Configuration Parameters in my .slx file (I changed cm^3/s into m^3/s for the flow rate) but it didn't have any effect on my .ssc file and I keep getting the error.
That function is not part of MATLAB. Anyway, this is not an issue with the matrix multiplication, because that cannot change. You are giving different matrices to the multiplication. Run the code step by step in each version of MATLAB (this is what the debugger is for, learn to use it!), and compare each of the intermediate values, until you see a difference. You just need to compare matrix sizes, because the error indicates you get a different size for at least one of the two operands. Once you know where the program starts to diverge, you know where to start looking for the problem.
I'm trying to simulate a satellite tracker. With ode45 I have de state of the satellite for each time and then convert position to Azimuth-Elevation local coordinates. If the object enters in the field of view (expressed as a mask of Az-El), the integration stops and changes the step to a smaller one in order to obtain more points inside. I'm trying to use an 'Events' function, which compares de Az-El of the satellite with the radar's mask. The problem is ode45 detects an event when it's not supposed to, and vice versa. I discarded the transformation to angular coordinates as the origin of the problem, and i tried to reduce the step size.Az-El plot load("maskmin.mat") load("maskmax.mat") Azmaskmin = maskmin(:,1); Elmaskmin = maskmin(:,2); Azmaskmax = maskmax(:,1); Elmaskmax = maskmax(:,2); t_total = []; y_total = []; az_total = []; el_total = []; t_actual = t0; y_actual = y0; options = odeset('RelTol',3e-14,'AbsTol',3e-14,'Refine',10,'NormControl','on',... 'Events', @(t,y) eventos_radar(t, y, lat_radar,... lon_radar, alt_radar,Azmaskmin,Azmaskmax,Elmaskmax,Elmaskmin)); aze = []; ele = []; yee = []; tee = []; % Principal loop r1 = 100; % Big step rt = 10; % Small step dt = r1; % Initial condition isn't inside FOV while t_actual < tf - dt [t, y, te, ye] = ode45(@(t,y)ecuacion_movimiento(t, y, mu),... [t_actual:dt:tf], y_actual, options); t_total = [t_total; t]; y_total = [y_total; y]; % Update next integration t_actual = t(end); y_actual = y(end,:)'; % Event check if ~isempty(ie) if dt == r1 dt = rt; fprintf('Entrance in t = %.2f segundos\n', t_actual); elseif dt == rt dt = r1; fprintf('Exit in t = %.2f segundos\n', t_actual); end t_actual = te(end); y_actual = ye(end, :)'; end end % Procesing results procesar_resultados(t_total, y_total, lat_radar, lon_radar, alt_radar,... Azmaskmin,Azmaskmax,Elmaskmax,Elmaskmin); function [value, isterminal, direction] = eventos_radar(t, y, lat_radar,... lon_radar, alt_radar,Azmaskmin,Azmaskmax,Elmaskmax,Elmaskmin) [az, el] = calcular_az_el(y(1:3)', lat_radar, lon_radar, alt_radar, t); if az>=Azmaskmax(1) && az<=Azmaskmax(end) el_min = interp1(Azmaskmin, Elmaskmin, az); el_max = interp1(Azmaskmax, Elmaskmax, az); value = [el_max - el, el - el_min]; isterminal = [1 1]; % Detect changes of sign else value = [Elmaskmax(1) - el, el - Elmaskmax(1)]; % Elmaskmax(1) is the El value from the FOV corner in order to get continuous values of 'value' when the object is % outside isterminal = [0 0]; % Ignores changes of sign end direction = [0 0]; 'Value'-time: The left plot is using the y_total values once the simulation stops, and the rigth plot is using the values of the y that the event function receives from the ode 45. Anyone knows what is going on? Any help is welcome!!
I think this is the answer: https://stackoverflow.com/questions/24647269. Note that passing Matlab objects to Java is **not supported** by Matlab. That is clear from the documentation.
How do I change a measurment unit in a Simscape custom block?
Out of range values when reading a MATLAB file with R.matlab
I have been trying to linearize a simple PLL model using the mixed signal blockset, and I can't manage to do it. What I don't understand, is that the block "Integer N Single Modulus" has the exact same blocks and you are able to plot a bode with it. However, when I try to place the block myself with the same configuration I get the following error when trying to linearise and plot the Bode: 'pll_filtre/Loop Filter3/Convert Sample Time' implements a Jacobian method, but failed to configure its Jacobian dimensions in the DoPostPropagationTasks function. Here is the PLL: I have tried to change the block "Loop Filter" for a Transfer Function of a second order loop filter, but I only got the following error: Error:Propagation delay input to pll_filtre/VCO/Variable Pulse Delay is negative. To obtain a causal simulation, the propagation delay must be positive. Here is the configuration of this test: I cannot find any of those errors online. How to linearize this simple PLL as it's done in the pre-made block?
IT++ is a C++ library of mathematical, signal processing and communication classes and functions. Its main use is in simulation of communication systems and for performing research in the area of communications. The kernel of the library consists of generic vector and matrix classes, and a set of accompanying routines. Such a kernel makes IT++ similar to MATLAB, GNU Octave or SciPy.
How can I get the same random results in IT++ and Matlab? For example, the default random generator algorithm in Matlab is "twister" which is "Mersenne Twister" with the keyword mt19937ar. So, when I write rng(0, "twister") in Matlab, the results are always the same (seed=0.) But, I don't know how to set it in IT++ to get to the same random results between Matlab and IT++. For testing, we can compare the rand(1,5) and randu(5) in Matlab and IT++, respectively.
If `A` is size `MxN` and `S` is size `MxNxZ` then `A-S` should work with implicit expansion since release R2016b to give you something the same size as `S`. If you're using an older version of MATLAB you'd need to use `bsxfun( @minus, S, A )`. Then you might need a different metric than `abs` to find the closest "slice" of the matrix, how are you defining that for a 2D matrix?
How to do A* Algorithm in Path Planing with Simulink ( Drone Navigation System )
MATLAB is throwing a warning and not plotting a geopolyshape when setting the ColorData field; however the shape is plotted when ColorData isn't set. The example code below demonstrates the issue. I am using MATLAB2024b. Note the latitude and longitude correspond to a H3 resolution 8 hexagon. I don't think the issue is because it's an H3 cell because other H3 cells plot fine with ColorData but I'm sharing for completeness. So how can I plot this geopolyshape while setting ColorData? MATLAB Warning: Warning: Error creating or updating TriangleStrip Error in value of property ColorData Array is wrong shape or size Example code lat = [41.9480823417544; ... 41.9232620388895; ... 41.9297343644414; ... 41.9610354203583; ... 41.9858827546380; ... 41.9794019931882; ... 41.9480823417544]; lon = [-71.5797574810054; ... -71.5494225035612; ... -71.5033771429879; ... -71.4876121649763; ... -71.5179362450247; ... -71.5640362454369; ... -71.5797574810054]; % Create geopolyshape shape = geopolyshape(lat, lon); figure; tiledlayout('flow'); nexttile; geoplot(shape,'FaceColor','b'); title('works') nexttile; geoplot(shape,'FaceColor','flat'); title('works') nexttile; geoplot(shape,'FaceColor','flat','ColorData',1); title('fails and throws warning') nexttile; geoplot(shape,'ColorData',5); title('fails and throws warning')
Oh boy... I really messed up. Sorry for bothering. 1. Yes, I was still on Debug Mode *facepalm*. I thought I switched to Release, but I didn't. 2. I simplified my minimal example to much. You are right with your reformulation but within my real algorithm this isn't working. When creating my example I was mor focussing on the operations rather than the numerical values. Anyway, problem is solved. Thanks!
The first problem is that the lines aren't parallel. The slope of the blue line is ~0.05442 while the slope of the red line is ~0.03997. But even if you make the slopes equal, given the precision of your points, you'll still probably have an error greater than 1e-5.
Nice analysis. For reference: The shortest, most efficient Eigen code is `M.noalias() = init * (r.array() + 1.).matrix();`, using a vector-vector outer product. `replicate` and any `rowwise()` operations are generally slow. But your guess is correct. The original code would be fast if OP hadn't forgotten to enable optimizations. Heck, even the [proper optimization mode for debugging , `-Og`](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) would solve the performance issue and get less than 1 second runtime
As you have discovered, MEX files are not currently supported on thread pools. However, MEX files are supported on process pools, i.e. try parpool("Processes")
Note that your installation method is likely incidental to your problem, given that both R and MATLAB seem to be working in principle. I'm not familiar with MATLAB, but the docs suggest that what you're likely looking for is the -batch parameter rather than -r, because only -batch "Logs text to stdout and stderr." If I understand the docs correctly, -batch is meant for non-interactive, CLI-only calls that behave like a console (terminal) application (which is what you're looking for), whereas -r is meant for opening the MATLAB GUI and executing a startup command there, at the start of an interactive session. Therefore, try the following: # Run MATLAB script and capture output # Note the use of -batch instead of -r, which should also obviate the need for # -nodesktop and -nosplash matlab_output <- system("matlab -batch \"run('model.m'); exit;\"", intern = TRUE)
Unable to find parallel lines- MATLAB code
I have two chirp signals "s1" and "s2" in MATLAB: % Parameter Setting R = 618e3; V = 7600; lambda = 0.0313; Fa = 5000; % Sampling Rate (Can't not Change) N = 10000; % Sample Points time_delay = 6.13e-5; % Axis Setting ta = ( -N/2 : N/2-1 )/Fa; fa = ( -N/2 : N/2-1 )*( Fa/N ); s1 = exp(-1j*2*pi/lambda*(V^2*(ta + time_delay).^2)/R); s2 = exp(-1j*2*pi/lambda*(V^2*(ta - time_delay).^2)/R); It is obvious that s1 has a positive shift (time_delay) on time axis ta, while the signal s2 has a negative shift on time axis. I need to make the two signals equal, which means s1-s2 equal to 0. Besides, these two signals are aliasing due to the sampling rate Fa is not high enough. I am unable to change the sampling rate and the length of the time axis, as these are determined by certain radar parameters. I tried to use the time shifting property in the Fourier transform. % Zero padding to avoid circular convolution s1 = [zeros(1,0.5*N), s1, zeros(1,0.5*N)]; s2 = [zeros(1,0.5*N), s2, zeros(1,0.5*N)]; fa2 = ( -N : N-1 )*( Fa/(2*N) ); % fa with padding (2N) % s1 Shifting By Fourier Property S1 = fftshift(fft(ifftshift(s1))); S1 = S1.*exp(-1j*2*pi.*fa2.*time_delay); s1r = fftshift(ifft(ifftshift(S1))); s1r = s1r(0.5*N+1:end-0.5*N); % s2 Shifting By Fourier Property S2 = fftshift(fft(ifftshift(s2))); S2 = S2.*exp(1j*2*pi.*fa2.*time_delay); s2r = fftshift(ifft(ifftshift(S2))); s2r = s2r(0.5*N+1:end-0.5*N); Result = s1r - s2r; figure(1); plot(ta,abs(Result)); xlabel("t(s)"); title('After Substraction'); However, the result is the following picture: The center part is quite low, but the two sides are very high and I think this is because the signals are aliasing. I don't know how to fix this problem. I would greatly appreciate any guidance or suggestions to help me resolve this issue.
@3CxEZiVlQ : The tag was incorrectly removed from the posting by Wolfie. A stl is a graphic format and is what the OP needs.
Save a structure in MATLAB data dictionary
If you change `line_segments(2,4) = 5.551825`, you'll get parallel lines. There's nothing wrong with your code, it's the data.
I'm having this error but I don't understand why. I'm creating a structure of size 3x4x4 with 6 fields within loops. Then, I would like to create two more fields for the whole structure. How can I do it? for i = 1:N for j=1:length(Cr) for m=1:length(TR) for k=1:length(pH) form(j,m,k).name = ["c" num2str(Cr(j)) "TR" num2str(TR(m)) "ph" num2str(pH(k))]; form(j,m,k).Cr = Cr(j); form(j,m,k).Ct = Cr(j)*TR(m); % corde tip form(j,m,k).S = (form(j,m,k).Cr+form(j,m,k).Ct)*H/2; form(j,m,k).AR = H^2./form(j,m,k).S; if (pH(k) == 0) form(j,m,k).c(i) = form(j,m,k).Ct*cos(phi(i))+form(j,m,k).Cr*(1-cos(phi(i))); elseif (yh(i) < H*pH(k)) form(j,m,k).c(i) = form(j,m,k).Cr; else form(j,m,k).c(i) = form(j,m,k).Cr+(form(j,m,k).Ct-form(j,m,k).Cr)/(H-pH(k)*H)*(yh(i)-pH(k)*H); endif end end end end form.c_top = form.c(N/2+1:end); form.c_bot = form.c(1:N/2); I would like that form(x,y,z).c_top = form(x,y,z).c(N/2+1:end), and this for the whole structure.
I looks like R.matlab is doing you a favour by omitting those characters. While I am not an SME, an internet search suggests those characters are often omitted from the affected species names so perhaps they are errors? At least there are only seven to deal with if you have to manually edit them. To examine the issue, you can use the rmatio package, as it will retain the non-UTF characters. library(rmatio) library(stringi) # Unzip .mat previously downloaded from # https://azti.sharepoint.com/sites/Proyectos/AMBI/Documentos%20compartidos/Forms/AllItems.aspx?id=%2Fsites%2FProyectos%2FAMBI%2FDocumentos%20compartidos%2FLibrary%2D2024%2Ezip&parent=%2Fsites%2FProyectos%2FAMBI%2FDocumentos%20compartidos&p=true&ga=1 # Edit file path where necessary unzip("data/AMBI/Library-2024.zip", files = "library.mat", exdir = "data/AMBI/") ambi <- read.mat("data/AMBI/library.mat") # Convert to df df <- data.frame(name = unlist(ambi$specieslist$name), group = unlist(ambi$specieslist$group), reassign = unlist(ambi$specieslist$reassign)) # Return rows containing non-UTF x <- df[which(stri_enc_mark(df$name) == "native"),] x$name # [1] "Congetia chesneyi\xfd" "Erythrops go\xfdsi" "Erythrops go\xfdsii" # [4] "Gymnonereis\xfdcrosslandi" "Hippolyte cura\xfdaoensis" "Neorhynchoplax\xfdsp." # [7] "Valencinia\xfdsp." # Convert non-UTF chars iconv(x$name, from = "macroman", to = "UTF-8") # [1] "Congetia chesneyi˝" "Erythrops go˝si" "Erythrops go˝sii" # [4] "Gymnonereis˝crosslandi" "Hippolyte cura˝aoensis" "Neorhynchoplax˝sp." # [7] "Valencinia˝sp." The closest encoding I could find was "macroman" but it is still not correct. Again, not an SME, but it appears that in some cases, those non-UTF characters are supposed to be either a "ë", or not there at all. If there is uncertainty, the only thing I can suggest is to contact the data maintainers to find out the correct encoding, or whether these are indeed errors. At least then you can rule out whether it's something to do with R.
I have error on part of code that called the preprocess lib. I tried main site and chat gpt but :) nothing for this part: for i1=1:L I=imread([FOLDEROpen ImagesName(i1).name]); [I X_]=PreProcess( I,Size1,Nbins,NWindow,NWindow ); X(fol,:,i1)=X_;
also to notify everyone, the most efficient answer by far that was recommended to me was [James Tursa's mex file](https://www.mathworks.com/matlabcentral/answers/2174161-need-to-vectorize-efficiently-calculating-only-certain-values-in-the-matrix-multiplication-a-b-us#answer_1560085) that does "masked matrix multiplication", and apparently "masked matrix multiplication" is a well defined concept so I will be looking into that. Thank you everyone for your help
Undocumented `hittest` no longer working as expected
Try the back tick instead backward slash.
I edited the question, should be clearer now @Wolfie
I successfully integrated MATLAB & R in macOS with Homebrew and Xcode Build Server (Apple Silicon). I made a step-by-step for that. However, I am failing when trying to do the same in Windows 10, and I am failing... successfully as well. I tried to make the same step-by-step. (1) Open PowerShell as Administrator Press Windows + S. Type PowerShell. Right-click on Windows PowerShell → Run as administrator. (2) Run the Command Again Now, with administrator permissions, run: Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.WebClient]::new().DownloadString('https://community.chocolatey.org/install.ps1') | Invoke-Expression This will correctly install Chocolatey. (3) Verify the Installation Once finished, check if it works by running: choco --version Expected output: 2.4.2 (or a similar version) INSTALL THE REQUIRED TOOLS (1) Now install the tools MATLAB needs: choco install gnuwin32-coreutils.install -y (2) Check the Location of the expr.exe File Open PowerShell as Administrator. Run the following command: dir "C:\" -Recurse -Filter expr.exe -ErrorAction SilentlyContinue What does it do? It searches for expr.exe across the C: drive. You should see a path like: C:\Program Files (x86)\GnuWin32\bin\expr.exe (3) Add the Path to the System PATH If the previous command returned a valid path, add it to the PATH: setx PATH "$($env:PATH);C:\Program Files (x86)\GnuWin32\bin" (4) Verify that the PATH Includes expr.exe Close and reopen PowerShell. Run: expr --version Check if MATLAB is in the PATH where matlab If it doesn't return MATLAB's path, you need to add it manually. Add MATLAB to the PATH Find MATLAB’s bin folder, for example: C:\Program Files\MATLAB\R2024b\bin Open PowerShell as Administrator and run: setx PATH "$($env:PATH);C:\Program Files\MATLAB\R2024b\bin" Close and reopen PowerShell. Final Step: Restart MATLAB Restart the computer if necessary. Open MATLAB as Administrator. Then, in macOS I had the following code and worked: # install.packages("R.matlab") library(R.matlab) # system("matlab -nodesktop -nosplash -r \"disp('MATLAB works!');exit;\"") # Save MATLAB code to file matlab_code <- " % MATLAB Model % Parameters alpha1 = 0.315; alpha2 = 0.100; alpha3 = 0.585; beta = 0.95; sigma = 0.40; deltak = 0.06; deltag = 0.05; rho = 0.95; % Initial Values Y = 1; C = 0.75; L = 0.3; K = 3.5; I = 0.25; G = 1; z = 1; e = 0; tau = 0.25; tauA = 0.22; lamda = 0.0303; % Model Equations for t = 1:1000 Y = z*(K^alpha1)*(G^alpha2)*(L^alpha3); C = (sigma/(1-sigma))*(1-L)*(1-tau)*((alpha3/(alpha1+alpha3))*Y/L); K = (Y - C) + (1 - deltak) * K; G = lamda * Y + (1 - deltag) * G; I = Y - C - (lamda * Y); z = exp(rho * log(z) + randn * 0.01); end % Display results disp(['Final Output: ', num2str(Y)]); " writeLines(matlab_code, "model.m") # Run MATLAB script and capture output matlab_output <- system("matlab -nodesktop -nosplash -r \"run('model.m'); exit;\"", intern = TRUE) # Print output for debugging print(matlab_output) # Find the line containing "Final Output:" final_line <- grep("Final Output:", matlab_output, value = TRUE) # Extract the numeric part using a regular expression final_value <- as.numeric(sub("Final Output: ", "", final_line)) # Print extracted value print(final_value) In Windows, R opens MATLAB displays the result but does not capture it and bring it to the environment. matlab_output <- system("matlab -nodesktop -nosplash -r \"run('model.m'); exit;\"", intern = TRUE)
I made some quick test and quite confirm above suspisions ... so i think i can workaround by temporarely replacing `WindowButtonMotionFcn` in `addlistener` event listener and restore everything at the end of the call ... I will make more clean code for workaround i'm thinking of.
@LuisMendo In figure 2, only the slow increase on the left needs consideration; regions with y>1e4 need be ignored.
When on remote desktop, Matlab creates a figure that is for half outside of the screen
Hm. yes but cell array of object is allowed..
Can I get raw camera data in matlab (before any conversion)
Draw decision boundary using Polynomial Kernel Function in SVM Matlab
Its inbuilt function so you can find it above. There is just issue with the just matrix multiplication in Task 5 snippet mention here. please use any data sets for that code.
chtz, pt 1: Yes! What you wrote using repmat is equivalent to expressing L as a Kronecker product of some matrix of 1s (e.g. ones(3,4)) with some smaller binary matrix you can call "L_block". The matrix of 1s can be any sized matrix of 1s (including ones(1)). I sort of exploited this kronecker product structure to perform my original post's solution under "Possible solution (need help vectorizing this code if possible)".
What driver support **does** the camera manufacturer provide on your platform? Which make, model and resolution is it? This sounds like Matlab not having recognised the camera properly and is making invalid assumptions about the data stream.
How big is your actual array? Because 5000x1 is tiny and it's not worth using a sparse array for. You need much, much larger arrays to make the sparse array overhead worth while.
The Wikipedia article on the topic is using the plane equation `ax+by+cz=d`, but my (and I believe yours as well, as we output the same coefficients) example uses the form `ax+by+cz+d=0`. When switching between them, the sign of `d` is flipped. Let me know if you find otherwise; I really don't mean to argue over semantics. Thanks for the dialogue!
I have matrices A (m by v) and B (v by n). I also have a logical matrix L (m by n). I am interested in calculating only the values in A * B that correspond to logical values in L (values of 1s). Essentially I am interested in the quantity ( A * B ) .* L . For my problem, a typical L matrix has less than 0.1% percent of its values as 1s; the vast majority of the values are 0s. Thus, it makes no sense for me to literally perform ( A * B ) .* L , it would actually be faster to loop over each row of A * B that I want to compute, but even that is inefficient. Possible solution (need help vectorizing this code if possible) My particular problem may have a nice solution given that the logical matrix L has a nice structure. Here's an example of L for a very small scale example (in most applications L is much much bigger and has much fewer 1-yellow entries, and many more 0-blue entries). This L matrix is nice in that it can be represented as something like a permuted block matrix. This L in particular is composed of 9 "blocks" of 1s, where each block of 1s has its own set of row and column indices, defining a particular submatrix in A * B. For instance, the highlighted area here can be seen the values of 1 as a particular submatrix in L. My solution was to do this: break the problem into submatrices over these blocks, and do matrix multiplications over each submatrix. I can get the row indices and column indices per each block's submatrix in L, organized in two cell lists "rowidxs_list" and "colidxs_list", both with the number of cells equal to the number of blocks. For instance in the block example I gave, subblock 1, I could calculate those particular values in A * B by simply doing A( rowidxs_list{1} , : ) * B( : , colidxs_list{1} ) . That means that if I precomputed rowidxs_list and colidxs_list (ignore the costs of calculating these lists, they are negligable for my application), then my problem of calculating C = ( A * B ) .* L could effectively be done by: C = sparse( m,n ) for i = 1:length( rowidxs_list ) C( rowidxs_list{i} , colidxs_list{i} ) = ... A( rowidxs_list{i} , : ) * B( : , colidxs_list{i} ); end This seems like it would be the most efficient way to solve this problem if I knew how to vectorize this for loop. Does anyone see a way to vectorize this? There may be ways to vectorize if certain things hold, e.g. only if rowidxs_list and colidxs_list are matrix arrays instead of cell lists of lists (where each column in an array is an index list, thus replacing use of rowidxs_list{i} with rowidxs_list(i,:) ). I'd prefer to use cell lists here if possible since different lists can have different numbers of elements. other suggested solution (creating a mex file?) I first posted this question on the /r/matlab subreddit, see here for the reddit thread. The user "qtac" recommended that a C-MEX function linking to C programming language: My gut feeling is the only way to really optimize this is with a C-MEX solution; otherwise, you are going to get obliterated by overhead from subsref in these loops. With C you could loop over L until you find a nonzero element, and then do only the row-column dot product needed to populate that specific element. You will miss out on a lot of the BLAS optimizations but the computational savings may make up for it. Honestly I bet an LLM could write 90%+ of that MEX function for you; it's a well-formulated problem. I think this could be a good solution to pursue, but I'd like other opinions as well.
to magnesium, chtz and Louis, , pt 1: yes regarding magnesium's comment, my solution in the original post (under "Possible solution (need help vectorizing this code if possible)") was me trying to exploit the periodicity of L. It can be shown that L is made up of a small number of submatrix "blocks": submatrices where all values are 1, in the example image I gave there are 9 blocks. So my solution (I'll call it "blocklooping") was to go over each block, and have a submatrix multiplication like A(rowidxs,:) * B(:,colidxs) to construct each block in C.
I am modeling a radar image based on my already modeled field of sea surface waves. Faced with the problem that the final image does not work right. It turns out to be some kind of nonsense. You can see the resulting image and what the field of surface waving looks like. The script in MATLAB looks like this (without taking into account main_prog from which all these functions are called). Functions of parameters: function [g, speed, dx, dy, x, y, df, f_start, f_end, dtt, theta] = common_data() g = 9.81; % acceleration of gravity speed = 13; % wind speed dx = 1; % step along the x-axis dy = 1; % step along the y-axis x = 0:dx:1000; y = 0:dy:1000; df = 0.1; % frequency range step f_start = 0.016; % frequency range start f_end = 1.25; % frequency range end dtt = pi / 18; % angle step theta = -pi/2:dtt:pi/2; % angle range end function [xd, alpha, wmaxd, wmax, gm] = JONSWAP_param(g, speed) xd = 2 * 10^(4); % acceleration parameter alpha = 0.076 * xd^(-0.22); % Phillips constant wmaxd = 3.5 * xd^(-0.33); % dimensionless frequency wmax = wmaxd * (g / speed); % max frequency of spectrum gm = 3.3; % gamma-factor end Spectrum calculations: function [JSP] = JONSWAP_Spec(g, alpha, wmax, gm, f) sgm = zeros(size(f)); EXP = zeros(size(f)); JSP = zeros(size(f)); for i = 1:length(f) if wmax >= f(i) sgm(i) = 0.07; else sgm(i) = 0.09; end EXP(i) = exp(- ( (f(i) - wmax)^2 ) / ( 2 * sgm(i)^2 * wmax^2) ); JSP(i) = alpha * g^(2) * (2*pi)^(-4) * ( (f(i))^(-5) ) * ( exp( (-5/4) * (f(i)/wmax)^(-4) ) ) * ( gm^(EXP(i)) ); % JONSWAP spectrum end end function [St, Swt, eta0] = Freq_Ang_Spec(dtt, theta, df, JSP) St = cos(theta).^(4); % angular spectrum Norm = trapz(dtt, St); Swt = JSP .* St'; % freq-angular spectrum eta0 = sqrt((2 * Swt .* df * dtt) ./ Norm); % amplitude of surface waving end Surface Waving simulation: function [phase, Kx, Ky, etaWA] = SurfaceWaving_simulator(g, x, y, theta, w, eta0) phase = 2*pi*rand(length(theta),length(w)); % initial phase t = 0; % time moment Kabs = (w.^2) / g; % wavenumber Kx = Kabs .* cos(theta)'; % projection of the wavevector on the x-axis Ky = Kabs .* sin(theta)'; % projection of the wavevector on the y-axis etaWA = zeros(length(x),length(y)); for i = 1:length(x) for j = 1:length(y) etaWA(i,j) = sum(eta0 .* cos(w * t - Kx * i - Ky * j + phase), 'all'); end end end RADAR data and RADAR image simulation: function [az_ang, inc_ang, slope_x, slope_y, Rfl_VV_s, Rfl_HH_s, K_rad, K_b, f_b] = Geom_Sig_Settings(g, x, y, etaWA) H_rad = 14; % radar height above sea level r = sqrt(x.^2 + y.^2); % horizontal distance R = sqrt(r.^2 + H_rad^2); % the trajectory of the signal to each point of the surface az_ang = atan2(y, x); % azimuth angle of the radar inc_ang = acos(H_rad./R); % angle of incidence graz_ang = pi/2 - inc_ang; % grazing angle % Calculation of local surface slopes (geometric modulation of the returned signal) [sx, sy] = gradient(etaWA); slope_x = atan(sx); % slope on x slope_y = atan(sy); % slope on y % Converting slopes to the radar coordinate system slope_rad_x = slope_x .* cos(az_ang) + slope_y .* sin(az_ang); slope_rad_y = -slope_x .* sin(az_ang) + slope_y .* cos(az_ang); % Calculation of geometric reflection coefficients Rfl_VV = @(inc_ang) (cos(inc_ang)).^(4) .* (1 + (sin(inc_ang)).^(2)).^(2) / (cos(inc_ang) + 0.111).^(4); % the square of the reflection coefficient module (case VV) Rfl_HH = @(inc_ang) (cos(inc_ang)).^(4) / (0.111 .* cos(inc_ang) + 1).^(4); % the square of the reflection coefficient module (case HH) Rfl_VV_s = sqrt(Rfl_VV(inc_ang + slope_rad_x)); % reflection coefficient module (case VV) Rfl_HH_s = sqrt(Rfl_HH(inc_ang + slope_rad_x)) + (slope_rad_y / sin(inc_ang)).^(2) .* sqrt(Rfl_VV(inc_ang)); % reflection coefficient module (case HH) %% Radar signal parameters c_light = 3 * 10^(8); % light speed f_rad = 10 * 10^(9); % the frequency of the radar signal emitted by the radar lambda_rad = c_light / f_rad; % the wavelength of the radar signal K_rad = (2*pi) / lambda_rad; % the wavenumber of the radar signal K_b = 2 * K_rad * sin(inc_ang); % the Bragg-Wolfe condition sigma = 0.073 / 997; f_b = sqrt(g * K_b + sigma * (K_b).^(3)) / (2*pi); % frequency of Bragg waves end function [JSP_b, RCS_VV] = RadBackscat_Simulator(g, alpha, wmax, gm, az_ang, Rfl_VV_s, Rfl_HH_s, K_rad, K_b, f_b) % Calculation of JONSWAP spectrum using f_B JSP_b = JONSWAP_Spec(g, alpha, wmax, gm, f_b); RCS_VV = 16 * pi * (K_rad)^4 .* (abs(Rfl_VV_s))^2 .* JSP_b; %RCS_HH = 16 * pi * (K_rad)^4 .* (abs(Rfl_HH_s))^2 .* JSP_b; %% Radar image visualization figure(3) imagesc(log10(RCS_VV)); colormap gray; colorbar; title('RADAR image'); xlabel('x'); ylabel('y'); end At the moment, I'm not sure what the problem might be, but nothing else comes to mind. I think the whole problem lies in the fact that my model does not take into account the position of the radar, because depending on the azimuthal angle az_ang and angle of incidence inc_ang at which the radar "looks" at a particular point on the ocean surface, the slope values slope_x slope_y will depend. That is, in fact, if we change the position of the radar, it will also change slopes. In my case, the slopes are counted without taking this fact into account. I tried to take this fact into account when calculating the slopes, but it didn't give any results: % Converting slopes to the radar coordinate system slope_rad_x = slope_x .* cos(az_ang) + slope_y .* sin(az_ang); slope_rad_y = -slope_x .* sin(az_ang) + slope_y .* cos(az_ang); What am I doing wrong? What could be the problem? I took the formulas for reflection coefficients here ( page 3 formulas (3),(4) & (6),(7) ): https://www.researchgate.net/publication/47652627_A_semiempirical_model_of_the_normalized_radar_cross-section_of_the_sea_surface_-_1_Background_model
@463035818_is_not_an_ai Could you also format what is quoted accordingly?
Suppose that I have a function defined on 0&lt;= x&lt;= pi, 0&lt;=y, z&lt;=2pi. I have written a matlab code to global search the maximum point, with step length 0.01. I also restored the function value. The code is (of course the function is more complicated than x+y+z. This is simply an example.) x=0; y=0; z=0; i=1; Maxdeviation= ComputeDeviationSum(0,0,0,mufT, mufD, mufC); MaximizingArg= [x, y,z] ; while x&lt;= pi y=0; z=0; while y&lt;= 2*pi z=0; while z&lt;=2 *pi deviation= x+y+z; % Just an example. The function is more complex. if deviation&gt; Maxdeviation MaximizingArg= [x, y,z]; Maxdeviation= deviation; end a(i,:)=[x, y,z, deviation]; z=z+0.01; i=i+1; end y=y+0.01; end x=x+ 0.01; end And I found this really slow. After I deleted the three lines restoring the value, i.e. deleted i=1; a(i,:)=[x, y,z, deviation]; i=i+1 these three lines, it became much faster. (I stopped the execution after 20 seconds and found the latter did 10 times more iteration than the former.) My question is: Why after stopping restoring value, the code is much faster? What should I do to let the code be faster if I want to restore the value for each point?
I have a Excel file with names of variables and their associated values as columns ash shown below: I would like to use them in my Simulink model as inputs, therefore I need them to load as variables individually and not as a table or an array. Please help me in achieving the following results in MATLAB workspace Thank you in advance. Moreover, if the file type needs to be changed to CSV or txt format, I could explore the option. P.S. I am not using dynamic variable evaluation. These are fixed parameters to be fed to the model.
I recently started working with data dictionaries in Matlab Simulink as it a efficient way to manage the data. I could assign entries for Matlab parameters etc.; however, I am trying to save a structure containing table data (multiple tables) in a data dictionary. The problem is if I simply add an entry using addEntry, I longer can access the internal tables and could see their values or names. Whereas I tried to add Datatype in Architectural section of data dictionary but I can't assign it in design data. So is there any way that I can assign a 1X1 struct with 7 fields containing tables in the design data section of data dictionary or I should assign the columns of tables to different variables in base workspace to save them as Matlab parameters by using addEntry? Sample code: DictionaryFile='myDictionary.sldd'; myDictionaryObj = Simulink.data.dictionary.open(DictionaryFile); toolDataSectObj=getSection(myDictionaryObj,'Design Data'); addEntry(toolDataSectObj,'TableData',TableStrucutre); Thank you.
Flag = 0; while Flag == 0 for x = 1:10 if x == 3 Flag = 1; end % end: if end % end; for end % end: while Can anyone tell me why the while loop condition is not triggering when x is three? It runs the entire for loop and I get a value of 10. I am trying to have a flag trigger when a specific condition is met in the for loop. Thank you!
I am fairly new to matlab and I managed to create a simulink model that tracks estimates using kalman filtering for position of drone but now I am supposed to implement A* Algorithm with my model, while I understand the Algorithm provided by the Matlab study, I dont know how I can connect it with my model. For reference, This is the reference generator ( movement control ) for my drone system and the Algorithm files I am using are from this link https://www.mathworks.com/matlabcentral/fileexchange/26248-a-a-star-search-for-path-planning-tutorial
Looks like you neither understood the [edit] nor the "add .. to the question" nor the "I will do thast for you...".
Indeed, I did some quick benchmarks and looks like `abs` does have sufficient overhead to makes the loop (without `sub2ind` as suggested by Cris in the comments) faster for a generic array, while this might be quicker for positive arrays
Fastest way to find first ZERO element of a sparse matrix
I am trying to convert a matlab function to its equivalent CUDA MEX function. Below is the matlab function: function [ShiftData_time] = simpledelayupdated_mat(RData, delay, fs) nfft = size(RData,1); binStart = floor(nfft/2); fftBin = (2*pi*ifftshift(((0:nfft-1)-binStart).'))/nfft; fftBin = fftBin'; RFFT = fft(RData, nfft, 1); ShiftData = RFFT .* ((exp(-1i * delay * fftBin)).'); ShiftData_time = ifft(ShiftData, nfft, 1); ShiftData_time = real(ShiftData_time); end Here is the CUDA implementation using MEX : #include "mex.h" #include <cuda_runtime.h> #include <cufft.h> #include <math.h> #define M_PI 3.14159 // Macro for cuFFT error checking. #define CUFFT_CHECK_ERROR(call) { cufftResult err = call; if(err != CUFFT_SUCCESS) { \ mexErrMsgIdAndTxt("CUDA:CUFFTError", "CUFFT error: %d", err); } } // Macro for CUDA runtime error checking. #define CUDA_CHECK_ERROR(call) { cudaError_t err = call; if(err != cudaSuccess) { \ mexErrMsgIdAndTxt("CUDA:RuntimeError", "CUDA error: %s", cudaGetErrorString(err)); } } // Updated CUDA kernel to apply the phase shift (delay) in the frequency domain. // Instead of launching one block per column with nfft threads, we now use a 2D grid. // grid.x corresponds to the column index, and grid.y is the number of blocks needed // to cover all frequency bins (with a fixed block size). __global__ void applyDelay(cufftDoubleComplex *data, const double *fftBin, double delay, int nfft, int nCols) { int col = blockIdx.x; // Column index. int blockId = blockIdx.y; // Block index within the column. int threadsPerBlock = blockDim.x; int threadId = threadIdx.x; // Compute global frequency bin index within this column. int index = blockId * threadsPerBlock + threadId; if (col < nCols && index < nfft) { int idx = col * nfft + index; double phase = -delay * fftBin[index]; double cosPhase = cos(phase); double sinPhase = sin(phase); cufftDoubleComplex factor; factor.x = cosPhase; factor.y = sinPhase; cufftDoubleComplex orig = data[idx]; cufftDoubleComplex result; result.x = orig.x * factor.x - orig.y * factor.y; result.y = orig.x * factor.y + orig.y * factor.x; data[idx] = result; } } // The MEX gateway function. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check input count: RData, delay, fs. if(nrhs != 3) mexErrMsgIdAndTxt("MATLAB:simpledelayupdated:invalidNumInputs", "Three inputs required: RData, delay, fs."); // Ensure RData is real and double precision. if(!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) mexErrMsgIdAndTxt("MATLAB:simpledelayupdated:inputNotDouble", "RData must be real double precision."); // Get input RData and its dimensions. double *RData = mxGetPr(prhs[0]); mwSize nfft = mxGetM(prhs[0]); // Number of rows. mwSize nCols = mxGetN(prhs[0]); // Number of columns. // Read scalar inputs: delay and fs (fs is provided for compatibility). double delay = mxGetScalar(prhs[1]); double fs = mxGetScalar(prhs[2]); // Not used directly. // Create output array (real, same size as input). plhs[0] = mxCreateDoubleMatrix(nfft, nCols, mxREAL); double *ShiftData_time = mxGetPr(plhs[0]); // Allocate host memory for complex input data. cufftDoubleComplex *h_complex = (cufftDoubleComplex*) mxMalloc(nfft * nCols * sizeof(cufftDoubleComplex)); for (mwSize col = 0; col < nCols; col++) { for (mwSize row = 0; row < nfft; row++) { int idx = col * nfft + row; h_complex[idx].x = RData[idx]; h_complex[idx].y = 0.0; } } // Precompute the FFT frequency bins. // This corresponds to the MATLAB expression: // fftBin = (2*pi*ifftshift(((0:nfft-1)-floor(nfft/2))))/nfft double *h_fftBin = (double*) mxMalloc(nfft * sizeof(double)); int binStart = (int)(nfft / 2); for (mwSize row = 0; row < nfft; row++) { int shifted_idx = (row + binStart) % nfft; int centered = row - binStart; h_fftBin[shifted_idx] = (2.0 * M_PI * centered) / (double)nfft; } // Allocate device memory for the complex data and the fftBin vector. cufftDoubleComplex *d_data; CUDA_CHECK_ERROR(cudaMalloc((void**)&d_data, nfft * nCols * sizeof(cufftDoubleComplex))); CUDA_CHECK_ERROR(cudaMemcpy(d_data, h_complex, nfft * nCols * sizeof(cufftDoubleComplex), cudaMemcpyHostToDevice)); double *d_fftBin; CUDA_CHECK_ERROR(cudaMalloc((void**)&d_fftBin, nfft * sizeof(double))); CUDA_CHECK_ERROR(cudaMemcpy(d_fftBin, h_fftBin, nfft * sizeof(double), cudaMemcpyHostToDevice)); // Create a cuFFT plan for batched 1D FFTs (each column is one FFT of size nfft). cufftHandle plan; int rank = 1; int n[1] = {(int)nfft}; int istride = 1, idist = nfft; int ostride = 1, odist = nfft; CUFFT_CHECK_ERROR(cufftPlanMany(&plan, rank, n, NULL, istride, idist, NULL, ostride, odist, CUFFT_Z2Z, nCols)); // Execute forward FFT (time to frequency domain). CUFFT_CHECK_ERROR(cufftExecZ2Z(plan, d_data, d_data, CUFFT_FORWARD)); // Launch the CUDA kernel to apply the phase shift. int threadsPerBlock = 256; // Use a safe block size. int blocksPerColumn = (nfft + threadsPerBlock - 1) / threadsPerBlock; dim3 grid(nCols, blocksPerColumn, 1); // grid.x: columns, grid.y: blocks per column. dim3 block(threadsPerBlock, 1, 1); applyDelay<<<grid, block>>>(d_data, d_fftBin, delay, nfft, nCols); CUDA_CHECK_ERROR(cudaDeviceSynchronize()); // Execute the inverse FFT to convert back to time domain. CUFFT_CHECK_ERROR(cufftExecZ2Z(plan, d_data, d_data, CUFFT_INVERSE)); // Allocate host memory for the inverse FFT result and copy from device. cufftDoubleComplex *h_result = (cufftDoubleComplex*) mxMalloc(nfft * nCols * sizeof(cufftDoubleComplex)); CUDA_CHECK_ERROR(cudaMemcpy(h_result, d_data, nfft * nCols * sizeof(cufftDoubleComplex), cudaMemcpyDeviceToHost)); // Normalize the result by dividing by nfft and take the real part. for(mwSize i = 0; i < nfft * nCols; i++) { ShiftData_time[i] = h_result[i].x / ((double)nfft); } // Clean up resources. cufftDestroy(plan); cudaFree(d_data); cudaFree(d_fftBin); mxFree(h_complex); mxFree(h_fftBin); mxFree(h_result); } This is how I am calling the Matlab function: [temp] = simpledelayupdated(gather(RF_Arr_gpu), scalarDelay, sampling_Freq); where RF_arr_gpu is a 2D MATLAB gpuArray, scalarDelay and sampling_Freq are scalars. The issue I'm facing is that the final output from both functions does not match when run on real data. However, I have tested individual components of the CUDA MEX function, and the differences between the MATLAB and CUDA MEX outputs are minimal. Can anyone help me identify where there could be issues in the code? I have attached the output from MATLAB and what we are currently getting from CUDA MEX. The MATLAB image is continuous while the CUDA MEX seems to be more discrete.
I've edited my question and provided my demo data and codes. Yes the output will have lot of zeros, as the number of element in each pixel of the 2d image will vary in a large range. Actually, what I'm dealing with is a FLIM (Fluorescence Lifetime Imaging Microscopy) dataset, and this conversion leads to a better adaptability for my following deep learning network training. It seems that my network cannot understand the histograms very well, so I'm thinking feeding those values directly into the network might help.
Just putting the value of the constant block as a parameter does not expose it to external access since when the code is generated it will be buried somewhere with local scope accessibility. You need to use the Simulink.Parameter object. To do so keep the model as it is and create in the workspace a the object with the same name as the variable you are passing to the constant: myCoinstantValue= Simulink.Parameter(); myCoinstantValue.CoderInfo.StorageClass = 'ExportedGlobal'; The ExportedGlobal property is the one that exposes the parameter to external access by making the parameter a global variable in the generated code. There is other properties you can set as default value, data type, unit, ... You should now be able to pass it either using the set_param or using system commands as you would with any other .exe
The ticklengths are both in your ax1 (also both in your ax2 which is the same as your ax1): data = [2000 2010 2020; 300 400 500; 50 40 30; 10 15 20]; yyaxis left; b = bar(data(2:end-1,:)', "stacked"); colororder('default') xticklabels(data(1, :)); ax1 = gca; ax1.YGrid = "on"; yyaxis right; l = plot(data(end, :), 'k'); l.LineWidth = 2; box off ax1.YAxis(1).Limits = [0 1000]; ax1.YAxis(2).Limits = [0 30]; ax1.YAxis(1).TickLength = [0 0]; ax1.YAxis(2).TickLength = [0 0];
In your code, M = repmat(init, [1, length(r)]); M = r.*M + init; r.*M is identical to r.*init. Adding one init to that is the same as incrementing r by one first. So, your MATLAB code is the same as M = (r + 1) .* init; This version is about twice as fast. repmat is hardly ever useful anymore since MATLAB introduced implicit singleton expansion (a.k.a. broadcasting). The right way to time code that is very fast like this is using timeit: r = [1, 2, 3, 4, 5]; init = ones(9, 1); timeit(@() func1(r, init)) timeit(@() func2(r, init)) function M = func1(r, init) M = repmat(init, [1, length(r)]); M = r .* M + init; end function M = func2(r, init) M = (r + 1) .* init; end Anyway, I am fairly sure that replicating this logic in Eigen will also produce much faster code. You will need to use .array(). On arrays, we can also use the operators *=, /=, * and / to perform coefficient-wise multiplication and division column-wise or row-wise. These operators are not available on matrices because it is not clear what they would do. [From "Broadcasting"] But if your Eigen code took 13 seconds to run, then you surely are using a debug build. You should never time a debug build (especially of C++ code), they turn off most optimizations. With Eigen, optimization can easily make a 10x or even a 100x difference.
I'm quite new to Matlab and I'm trying to convert 512*512 histograms to a 3d matrix. The following loop works fine but is quite slow especially when x and y increase. The timer in Matlab tells me that repelem function costs ~90% of time: %% to generate input_hist input_hist = zeros(512,512,3125,'uint16'); [xdim, ydim, binNum] = size(input_hist); max_count = 5000; for x = 1:xdim for y = 1:ydim total_count = randi([0, max_count]); hist_vector = randi([0,31], 1, binNum); current_sum = sum(hist_vector); hist_vector = uint16(hist_vector * (total_count / current_sum)); input_hist(x, y, :) = hist_vector; end end elementNum = sum(input_hist, 3); maxElementNum = max(elementNum(:)); minElementNum = min(elementNum(:)); %% to generate values values = 4:4:12500; binNum_ = length(values); % should be the same with binNum %% loops tic; output_vals_loops = zeros(xdim, ydim, maxElementNum, 'single'); % fill with 0s for x = 1:xdim for y = 1:ydim elementNumHere = elementNum(x,y); if elementNumHere &gt; 0 valuesHere = repelem(values, squeeze(input_hist(x,y,:))); output_vals_loops(x,y,1:elementNumHere) = valuesHere; end end end toc; input_hist is a 3d uint16 (512×512×3125), values is a vector (3125×1) corresponding to the 3rd demension of input_hist, maxElementNum = ~5000 and there are lots of zeros in elementNum. I searched the Internet but find no good solutions. Is there a faster way for me to do this conversion? 10X faster for example? Is it possible to avoid the loops? Or do I really have to use the function repelem?
@asdjkh, "the grayscale image created using my custom code have slightly different values. " --> What is an example those those different values? What was R,G,B?
Luis thanks for the nice vectorized solution, but I'm actually getting it slower than the other options. Given the limited memory on my current computer, I tested your code with large data (my main concern case) for a certain large data size handleable by my computer. E.g., I tested when 2e-2% of the entries were 1s in L, and A * B was (m=5625 by n=90000). Here your method took around 63.1 seconds sec, vs 18.8 sec for (A * B) , and 28.5 sec for (A * B) .* L. this ratio was about the same for any value of v. I'm not clear why, maybe matlab is not that well optimized for indexing...
Can you also add a screenshot of the data you have in your spreadsheet?
As described in this answer (to the question you already linked in your question), the scalar box constraint C defines a penalty on the sum of slack variables. In the dual optimization problem, this corresponds to an upper bound to the Lagrange multipliers, hence the name "Box Constraint". As you mention, this is a scalar, not a vector. The BoxConstraints property is, however, a n-by-1 vector, where n is the number of training observations. Note that when calling fitcsvm you can only set C to a scalar and not a vector, so the BoxConstraints property is internally calculated. In the Algorithms section of the fitcsvm function documentation, MATLAB specifies, what actually happens under the hood (highlighting by me): For two-class learning, fitcsvm assigns a box constraint to each observation in the training data. The formula for the box constraint of observation j is Cj = nC0wj* where C0 is the initial box constraint, and wj* is the observation weight adjusted by Cost and Prior for observation j. The concept of Cost, Prior and Weight is further documented here .When calling fitcsvm, you can specify a Cost, Prior and/or Weights: With a Cost matrix C (caution, also letter C but now used as a cost and not as the box constraint!), you can specify the cost of misclassifying an observation For K classes, it is a K-by-K matrix where cij is the cost of classifying an observation of class i into class j The prior p is a vector containing the prior probabilities for all classes. The weight w allows you to specify an arbitrary weight for that observation. From these values, MATLAB calculates an adjusted weight wj*, which is then used by fitcsvm as shown above to scale the Box Constraint individually for each observation. The result of this calculation is saved in the BoxConstraints property of the ClassificationSVM class. Hence, the BoxConstraints contains a weighted version for every observation j of the standard box constraint that you specified. tl;dr: fitcsvm adjusts the scalar box constraint C to account for prior probabilities, misclassification costs and/or observation weights that you specify. If you use default values for these, the BoxConstraints will just be C for all values - which is exactly what you see.
Reducing initial values 512 and 3125 to 1/10th the time cost is divided 1/3 on 1st for loop and 2/3 on 2nd for loop. Roughly 20 seconds 1st for loop, about 40 seconds 2nd loop. The following is not optimal, and it probably the sizes of some intermediate variables may have to changed, but the point is that tic toc measurements, one for each for loop, both fall from 20s and 40s down to 0.01s each. So here you have it : % k1=512; % k2=3125; k1=51; k2=312; %% to generate input_hist input_hist = zeros(k1,k1,k2,'uint16'); [xdim, ydim, binNum] = size(input_hist); max_count = 5000; TC=randi([0, max_count],1,xdim*ydim); HV=randi([0,31], xdim*ydim, binNum); tag1=tic; for x = 1:xdim for y = 1:ydim total_count = TC(x+y-1); % randi([0, max_count]); hist_vector = HV(x+y-1,:); % randi([0,31], 1, binNum); current_sum = sum(hist_vector); hist_vector = uint16(hist_vector * (total_count / current_sum)); input_hist(x, y, :) = hist_vector; end end t1=toc(tag1) elementNum = sum(input_hist, 3); maxElementNum = max(elementNum(:)); minElementNum = min(elementNum(:)); %% to generate values values = 4:4:12500; binNum_ = length(values); % should be the same with binNum tag2=tic; output_vals_loops = zeros(xdim* ydim, maxElementNum); % fill with 0s valuesHere=[]; elementNumHere=[]; for x = 1:xdim for y = 1:ydim elementNumHere = [elementNumHere elementNum(x,y)]; % if elementNumHere &gt; 0 % valuesHere = repelem(values, squeeze(input_hist(x,y,:))); % valuesHere = [valuesHere repelem(values, input_hist(x+y-1))]; % output_vals_loops(x+y,1:elementNumHere) = valuesHere; % end end end for x = 1:xdim for y = 1:ydim if elementNumHere &gt; 0 valuesHere = [valuesHere repelem(values, input_hist(x+y-1))]; end end end t2=toc(tag2) Obviously these 2 valuesHere=[]; elementNumHere=[]; can be improved. But the point is that the delay has gone down x1000 . Also, note I have split 2nd for loop into 2 for loops.
I'm running a MATLAB script on macOS that performs sensor fusion using GNSS and IMU data. The script runs perfectly in MATLAB R2024 but fails in MATLAB R2022 with the following error during the ECEF to ECI frame transformation: === Task 5: ECI and ECEF Frame Plotting === Error using * Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication. Error in untitled3&gt;transform_ecef_to_eci_gnss (line 332) pos_eci(i,:)= (Rz* pos_ecef(i,:).').'; Error in untitled3 (line 121) transform_ecef_to_eci_gnss(T_gnss, EARTH_ROTATION_RATE); I suspect there might be differences between MATLAB R2022 and R2024 that affect this function. I've confirmed that all required files and dependencies are present and that the MATLAB path is set correctly in both environments. Below is the relevant portion of my code: function Fusion_ECI_Corrected() % FUSION_ECI_CORRECTED % Enhanced GNSS and IMU Fusion in ECI Frame with Corrected Gravity Compensation and Drift Correction, % using load_nav_data(). %% Task 0: Configuration [IMU_Data, GNSS_Data, fsIMU, fsGNSS] = load_nav_data(); T_imu = struct2table(IMU_Data); T_gnss = struct2table(GNSS_Data); % Rename velocity fields if necessary if ismember('Velocity_X', T_gnss.Properties.VariableNames) T_gnss.Properties.VariableNames{'Velocity_X'} = 'VX_ECEF_mps'; end if ismember('Velocity_Y', T_gnss.Properties.VariableNames) T_gnss.Properties.VariableNames{'Velocity_Y'} = 'VY_ECEF_mps'; end if ismember('Velocity_Z', T_gnss.Properties.VariableNames) T_gnss.Properties.VariableNames{'Velocity_Z'} = 'VZ_ECEF_mps'; end % Constants EARTH_ROTATION_RATE = 7.2921159e-5; % (Other constants and processing steps...) %% Task 5: ECI and ECEF Transform &amp; Plot fprintf('\n=== Task 5: ECI and ECEF Transform &amp; Plot ===\n'); [pos_eci_gnss, vel_eci_gnss, acc_eci_gnss, ... pos_ecef_gnss, vel_ecef_gnss, acc_ecef_gnss] = transform_ecef_to_eci_gnss(T_gnss, EARTH_ROTATION_RATE); % (Rest of the code for storing and plotting data) end function [pos_eci, vel_eci, acc_eci, pos_ecef, vel_ecef, acc_ecef] = transform_ecef_to_eci_gnss(T_gnss, EARTH_ROTATION_RATE) t_rel = T_gnss.Posix_Time - T_gnss.Posix_Time(1); theta = -EARTH_ROTATION_RATE .* t_rel; cos_t = cos(theta); sin_t = sin(theta); pos_ecef = [T_gnss.X_ECEF_m, T_gnss.Y_ECEF_m, T_gnss.Z_ECEF_m]; vel_ecef = [T_gnss.VX_ECEF_mps, T_gnss.VY_ECEF_mps, T_gnss.VZ_ECEF_mps]; n = length(theta); pos_eci = zeros(n, 3); vel_eci = zeros(n, 3); for i = 1:n Rz = [cos_t(i), -sin_t(i), 0; sin_t(i), cos_t(i), 0; 0, 0, 1]; pos_eci(i, :) = (Rz * pos_ecef(i, :)').'; vel_eci(i, :) = (Rz * vel_ecef(i, :)').'; end dt = mean(diff(T_gnss.Posix_Time)); acc_eci = zeros(n, 3); acc_ecef = zeros(n, 3); for i = 2:n acc_eci(i, :) = (vel_eci(i, :) - vel_eci(i-1, :)) / dt; acc_ecef(i, :) = (vel_ecef(i, :) - vel_ecef(i-1, :)) / dt; end acc_eci(1, :) = acc_eci(2, :); acc_ecef(1, :) = acc_ecef(2, :); end Here is the load_nav_data function : function [IMU_Data, GNSS_Data, fsIMU, fsGNSS] = load_nav_data() % LOAD_NAV_DATA Loads IMU and GNSS data from files. % % [IMU_Data, GNSS_Data, fsIMU, fsGNSS] = load_nav_data() % % - IMU data is read from a .dat file (without header) and is expected to % have 10 columns in the order: % Message_Counter, Sample_Time, Gyro_X, Gyro_Y, Gyro_Z, % Accel_X, Accel_Y, Accel_Z, Temperature, Status. % % - GNSS data is read from a .csv file (with one header row). The file is % assumed to have 20 columns with the following order: % 1) UTC_yyyy % 2) UTC_MM % 3) UTC_dd % 4) UTC_HH % 5) UTC_mm % 6) UTC_ss % 7) Posix_Time % 8) Latitude_deg % 9) Longitude_deg % 10) Height_deg (stored as Height_m) % 11) X_ECEF_m % 12) Y_ECEF_m % 13) Z_ECEF_m % 14) VX_ECEF_mps -&gt; Velocity_X % 15) VY_ECEF_mps -&gt; Velocity_Y % 16) VZ_ECEF_mps -&gt; Velocity_Z % 17) HDOP % 18) VDOP % 19) PDOP % 20) TDOP % % The function also prompts for the IMU and GNSS sampling frequencies. % % Author: Your Name % Date: YYYY-MM-DD %% Select IMU Data File (.dat, no header) [imuFile, imuPath] = uigetfile('*.dat', 'Select IMU file (.dat format)'); if isequal(imuFile, 0) error('No IMU file selected.'); end imuFullFile = fullfile(imuPath, imuFile); imuRaw = readmatrix(imuFullFile); if size(imuRaw,2) ~= 10 error('IMU data must have exactly 10 columns.'); end % Build IMU_Data structure (each field as a 1xN row vector) IMU_Data.Message_Counter = imuRaw(:,1).'; IMU_Data.Sample_Time = imuRaw(:,2).'; IMU_Data.Gyro_X = imuRaw(:,3).'; IMU_Data.Gyro_Y = imuRaw(:,4).'; IMU_Data.Gyro_Z = imuRaw(:,5).'; IMU_Data.Accel_X = imuRaw(:,6).'; IMU_Data.Accel_Y = imuRaw(:,7).'; IMU_Data.Accel_Z = imuRaw(:,8).'; IMU_Data.Temperature = imuRaw(:,9).'; IMU_Data.Status = imuRaw(:,10).'; %% Select GNSS Data File (.csv) [gnssFile, gnssPath] = uigetfile('*.csv', 'Select GNSS file (.csv format)'); if isequal(gnssFile, 0) error('No GNSS file selected.'); end gnssFullFile = fullfile(gnssPath, gnssFile); % Read GNSS file, skipping the header row (assumes one header row) GNSS_raw = readmatrix(gnssFullFile, 'NumHeaderLines', 1); if size(GNSS_raw,2) ~= 20 error('GNSS data must have exactly 20 columns.'); end % Build GNSS_Data structure using fixed column indices. GNSS_Data.UTC_yyyy = GNSS_raw(:,1).'; GNSS_Data.UTC_MM = GNSS_raw(:,2).'; GNSS_Data.UTC_dd = GNSS_raw(:,3).'; GNSS_Data.UTC_HH = GNSS_raw(:,4).'; GNSS_Data.UTC_mm = GNSS_raw(:,5).'; GNSS_Data.UTC_ss = GNSS_raw(:,6).'; GNSS_Data.Posix_Time = GNSS_raw(:,7).'; GNSS_Data.Latitude_deg = GNSS_raw(:,8).'; GNSS_Data.Longitude_deg = GNSS_raw(:,9).'; % Although the header is Height_deg, we store it as Height_m here. GNSS_Data.Height_m = GNSS_raw(:,10).'; GNSS_Data.X_ECEF_m = GNSS_raw(:,11).'; GNSS_Data.Y_ECEF_m = GNSS_raw(:,12).'; GNSS_Data.Z_ECEF_m = GNSS_raw(:,13).'; GNSS_Data.Velocity_X = GNSS_raw(:,14).'; GNSS_Data.Velocity_Y = GNSS_raw(:,15).'; GNSS_Data.Velocity_Z = GNSS_raw(:,16).'; GNSS_Data.HDOP = GNSS_raw(:,17).'; GNSS_Data.VDOP = GNSS_raw(:,18).'; GNSS_Data.PDOP = GNSS_raw(:,19).'; GNSS_Data.TDOP = GNSS_raw(:,20).'; %% Prompt user for sampling frequencies prompt = {'Enter IMU Sampling Frequency (Hz):', 'Enter GNSS Sampling Frequency (Hz):'}; answer = inputdlg(prompt, 'Sampling Frequencies', [1 50], {'400','10'}); if isempty(answer) error('Sampling frequency input cancelled.'); end fsIMU = str2double(answer{1}); fsGNSS = str2double(answer{2}); if isnan(fsIMU) || isnan(fsGNSS) || fsIMU &lt;= 0 || fsGNSS &lt;= 0 error('Invalid sampling frequencies.'); end %% Save sampling frequencies for future use. SAMPLE_FREQ = fsIMU; GNSS_FREQ = fsGNSS; save('sampling_frequencies.mat', 'SAMPLE_FREQ', 'GNSS_FREQ'); disp(['IMU Sampling Frequency: ' num2str(SAMPLE_FREQ) ' Hz']); disp(['GNSS Sampling Frequency: ' num2str(GNSS_FREQ) ' Hz']); end What I've Tried: Verified that all file paths and dependencies are correct in both MATLAB R2022 and R2024. Reviewed MATLAB’s documentation for any changes related to matrix multiplication or file I/O between versions. My Question: Has anyone encountered similar version-specific issues with matrix multiplication in MATLAB? Are there known changes between MATLAB R2022 and R2024 that could cause this error in the transform_ecef_to_eci_gnss function? How can I adjust my code to ensure compatibility with the older version? Additional Details: MATLAB R2024: Works fine MATLAB R2022: Fails with the error above OS: macOS
@Cris I thought about skipping `sparse`, but I assume it's needed because OP says that looping over the nonzero entries is slow and that `L` has density 0.1%, which sounds like `L` and `C` are big matrices. As for `dot`, it adds the usual input-checking overhead and then does the same as my last line. Except it also has an unwanted conjugate :-)
I need to make a table that has column names "Radii", "SurfaceA", and "Volume". But when I display the table it names the columns "Var1", "Var2", and "Var3". What is causing this? Im also brand new to Matlab, if there's some easy way to optimize this please let me know. Radii = [0.050:0.050:0.300]; SurfaceA = []; Volume = []; for i = 1:length(Radii) SurfaceA(i) = 4*pi*Radii(i)^2; Volume(i) = (4*pi*Radii(i)^3)/3; end Sphere = table(Radii',SurfaceA',Volume'); disp("#1") disp("Sphere = ") fprintf("\n") disp(Sphere) This returns #1 Sphere = Var1 Var2 Var3 ____ ________ _________ 0.05 0.031416 0.0005236 0.1 0.12566 0.0041888 0.15 0.28274 0.014137 0.2 0.50265 0.03351 0.25 0.7854 0.06545 0.3 1.131 0.1131 Should be #1 Sphere = Radii Surface A Volume ____ ________ _________ 0.05 0.031416 0.0005236 0.1 0.12566 0.0041888 0.15 0.28274 0.014137 0.2 0.50265 0.03351 0.25 0.7854 0.06545 0.3 1.131 0.1131
The distance between a point and a plane will be the length of a line normal to the plane which intersects the point. Given that, this question has three distinct parts, as I see it. Create a plane based on 3 clustered points Calculate lines normal to that plane which also go through specified points Get the length of those lines between the points and plane intersections Plotting A great resource for this problem can be found here. Aspects of this answer are modified snippets from that article, and I recommend giving it a read. The function you used is well suited for plotting plane meshes. The normal calculation, as you included, is also very useful. However, since we need to calculate intersection points on the plane, having a function version of the plane is helpful. To do this, I have used scalar symbolic vars and functions. function [normal, planefunction, solvedplanefunction, P] = generate_plane(p1, p2, p3) normal = cross(p1 - p2, p1 - p3); % get the normal syms x y z P = [x, y, z]; planefunction = dot(normal, P - p1); % define a function version of the plane solvedplanefunction = solve(planefunction, z); % solve this function for z (used later) end The next step is to calculate the lines normal to the plane which intersect given points. Since we have the equation for the plane, and a version of it solved for z, this is pretty straightforward. First, we need to create a line that starts at our point, and has the same normal as our plane. Then we just need to solve for when that line's equation is equal to our plane's equation. function [closest_point] = generate_closest_planar_point(normal, planefunction, P, point) syms t line = point + t*normal; % create line equation tempfunction = subs(planefunction, P, line); t0 = solve(tempfunction); % get value of t where the equations are equal closest_point = subs(line,t,t0); % plug in t0 to line equation to get point end With that, most of our problem is solved. Essentially, we need to calculate the norm of each of our calculated line segments, and plot the planes and line segments. So, setting the problem up with arbitrary points that comprise objects m and n: % defining the objects ObjectM_A = [1 1 1]; ObjectM_B = [2 0 2]; ObjectM_C = [1 3 3]; ObjectN_A = [3 3 3]; ObjectN_B = [2 2 9]; ObjectN_C = [1 4 2]; % creating the plane for m figure() [normalM, planeM, solvedplaneM, PM] = generate_plane(ObjectM_A, ObjectM_B, ObjectM_C); fsurf(solvedplaneM, [-5 5 -5 5]), hold on % plot the mesh by its function % creating the plane for n [normalN, planeN, solvedplaneN, PN] = generate_plane(ObjectN_A, ObjectN_B, ObjectN_C); fsurf(solvedplaneN, [-5 5 -5 5]) % for each pt in m, find the closest point on n % print the distance for pt = {ObjectM_A, ObjectM_B, ObjectM_C} cur = pt{1}; cur_closest = double(generate_closest_planar_point(normalN, planeN, PN, cur)); plot3([cur_closest(1) cur(1)], [cur_closest(2) cur(2)], [cur_closest(3) cur(3)], 'r','LineWidth', 2); hold on fprintf(strcat("Object M, point: [", num2str(cur), "] -> [", num2str(cur_closest), "](length = ", string(norm(cur-cur_closest)),")\n")) end % for each pt in n, find the closest point on m % print the distance for pt = {ObjectN_A, ObjectN_B, ObjectN_C} cur = pt{1}; cur_closest = double(generate_closest_planar_point(normalM, planeM, PM, cur)); plot3([cur_closest(1) cur(1)], [cur_closest(2) cur(2)], [cur_closest(3) cur(3)], 'b','LineWidth', 2); hold on fprintf(strcat("Object N, point: [", num2str(cur), "] -> [", num2str(cur_closest), "](length = ", string(norm(cur-cur_closest)),")\n")) end % plotting points plot3(ObjectM_A(1),ObjectM_A(2),ObjectM_A(3),'r.','Markersize',25) plot3(ObjectM_B(1),ObjectM_B(2),ObjectM_B(3),'r.','Markersize',25) plot3(ObjectM_C(1),ObjectM_C(2),ObjectM_C(3),'r.','Markersize',25) plot3(ObjectN_A(1),ObjectN_A(2),ObjectN_A(3),'b.','Markersize',25) plot3(ObjectN_B(1),ObjectN_B(2),ObjectN_B(3),'b.','Markersize',25) plot3(ObjectN_C(1),ObjectN_C(2),ObjectN_C(3),'b.','Markersize',25) zlim([-5 5]);
If there’s a difference, it most likely is in the exact weights used for red, green and blue.
So I'm looking to create a custom RL agent in matlab where the environment is provided by a Simulink model. Before I was using Matlab built in rlDDPGAgent object as my agent and then use the train(agent, env) built in function to perform my training where agent = rlDDPGAgent object and env = rlSimulinkenv object. Then the train() built in function does the simulation loop for me internally. But now since I'm creating a custom Agent, I'm assuming I can't use train() built in function anymore. Would I have to just create my own training loop in matlab script? And how would I get feed my actions into my Simulink environment and acquire the next state? I'm not looking for line by line code by just a general direction/format I can follow to start. Thanks
Help me understand your question better. So, you have 2 3-point clusters(the two clusters you listed are identical, which I assume is an error). Are you asking for the distance between the planes created by each cluster? If so, note that this is only applicable when the planes are parallel, because the distance between planes is non-constant. Or, are you trying to find the distance that points in the other cluster are from the plane? If so, do you want all of the points or just a specific one? I ask because you use `X` in your final, `dot()` call, but that is not defined anywhere.
You directly have an example in the documentation of a second order equation with initial conditions on the unknown function and its derivative. Applying it to your problem gives: syms i(t) R L C V0 % Define component values R = 10; L = 1; C = 1; V0 = 12; % Define the differential equation eqn = L*diff(i, t, 2) + R*diff(i, t) + (1/C)*i == 0; % Define initial conditions Di = diff(i,t); init_cond = [i(0)==0, Di(0)==V0/L]; % Solve the differential equation with initial conditions iSol(t) = dsolve(eqn, init_cond); % Display the particular solution disp('Particular Solution for i(t):') disp(iSol(t)) Edit: I have called the unknown i, like you did, but it is good practice not to use i (or j) as variable names in Matlab. Edit 2: It seems like the variable in the differential equation governing the behavior of a RLC circuit should be the charge q instead of the current i. Nonetheless the equation is right (if solving for the charge)
How to use low-frequency filtering to process the rising signal
How to solve this error using "trainNetwork" on Matlab
@Millemila You can edit the [startup script](https://www.mathworks.com/help/matlab/ref/startup.html) or just have a standard (standalone) function/script which you run before running any other relevant code - maybe you have a file you already run before you start working which sorts out your paths etc where you could include it. This does not need editing into all of your other code, you just run it once before other stuff.
Thank you. Can you please discuss a way to have it done without changing all codes? Please show what "on startup" means. Where is the startup file? what should i write in there?
My strain time-domain data shown in figure 1 contains significant high-frequency noise. The segment I focus on is the strain rising phase shown in figure 2, where the amplitude can be truncated at 1e4. When applying FFT-based low-frequency filtering, I found that the selected time duration of the filtering region significantly affects the filtering results. How should I resolve this issue? signal-data clc;clear;close all; %% load data load('20250310signal1.mat'); t=ttt'; y=yyy'; %% fs = fix(1/(t(2)-t(1))); n = length(y); Y = fft(y); f = (0:n-1)*(fs/n); %% Low-pass filtering (retain DC and low-frequency components) cutoff = 12500; % cut-off frequency Y_filtered = Y; Y_filtered(f &gt; cutoff) = 0; %% Inverse FFT to obtain filtered signal y_filtered = ifft(Y_filtered, 'symmetric'); %% Plot results figure; plot(t, y);hold on; plot(t, y_filtered); xlabel('Time (s)'); ylabel('Amplitude'); legend('data','filtered data')
repelem can be used once to compute the histogram. All other operations are needed for placing the input arrays in the correct order: output_values = zeros(maxElementNum, xdim, ydim); vals = repmat(reshape(values, [], 1), xdim * ydim, 1); mask = reshape(elementNum, 1, xdim, ydim) &gt;= (1:maxElementNum).'; output_values(mask) = repelem(vals, reshape(permute(input_hist, [3, 1, 2]), [], 1)); output_values = ipermute(output_values, [3, 1, 2]);
I have been trying to solve this issue with out any luck so far. From the Coursera course "Introduction to Data, Signal, and Image Analysis with MATLAB" the below code is retrieved. I'm trying to see if I can get this working in Octave 9.2. But that result in the error: error: contourc: X, Y, and Z must be real numeric matrices error: called from contourc at line 110 column 5 contour at line 146 column 14 contour at line 80 column 18 classification1 at line 19 column 3 The class of X, Y and cls is double and the size of all 3 is 4x8. Reading this post: Octave Contour plots The contour function works fine. No error. But with the code: function classification1() load fisheriris pkg load statistics [~,~,s] = unique(species); figure(1); plot(meas(s==1 ,1), meas(s==1, 2), 'rx') hold on plot(meas(s==2 ,1), meas(s==2, 2), 'go') plot(meas(s==3 ,1), meas(s==3, 2), 'b*') xlabel('Feature 1'); ylabel('Feature 2'); legend('setosa', 'versicolor', 'virginica'); [X,Y] = meshgrid(4:.01:8, 2:.01:4.5); cls = my_iris_classifier([X(:), Y(:)]); cls = reshape(cls, size(X)); contour(X, Y, cls==1,[1,1], 'r--'); contour(X, Y, cls==2, [1, 1], 'g--'); contour(X, Y, cls==3, [1, 1], 'b--'); endfunction function class = my_iris_classifier(feat) class = zeros(size(feat,1),1); for i = 1:size(feat,1); if feat(i,1) > 6 class(i) = 3; elseif feat(i,2) > 3 class(i) = 1; else class(i) = 2; endif endfor endfunction it doesn't.
How to get 'Live Editor Evaluation Helper' .m file name from live script through another live script?
I am using code using the trainNetwork function with MATLAB to train and predict some data, however I am getting this error message "Invalid training data. Y must be a vector of categorical responses." I am using some training Data and validation data for a system with 4 inputs and 1 output and I want to train my model. DATA sizes are: Training DATA>> Training inputs data of the size: (1973, 4), Training output data of the size: (1973, 1). Validation DATA>> Validation inputs data of the size: (120, 4), validation output data of the size:(120, 1) I tried to change the size of DATA, transposed them and convert them to categorical form, but I am getting a second message error which is: "Number of observations in X and Y disagree" Code used: XTrain=Input_Train YTrain=Output_train XValidation=Input_val YValidation=Output_val layers = [ imageInputLayer([28 28 1]) convolution2dLayer(3,8,'Padding','same') batchNormalizationLayer reluLayer maxPooling2dLayer(2,'Stride',2) convolution2dLayer(3,16,'Padding','same') batchNormalizationLayer reluLayer maxPooling2dLayer(2,'Stride',2) convolution2dLayer(3,32,'Padding','same') batchNormalizationLayer reluLayer fullyConnectedLayer(10) softmaxLayer classificationLayer]; options = trainingOptions('sgdm', ... 'MaxEpochs',8, ... 'ValidationData',{XValidation,YValidation}, ... 'ValidationFrequency',200, ... 'Verbose',false, ... 'Plots','training-progress'); net = trainNetwork(XTrain,YTrain,layers,options)
If you apply low-pass filtering to remove high-frequency noise, that is also going to soften the sharp rise, because the rise is composed of high frequencies. I don't think you can avoid that if you use (linear, time-invariant) filtering. However, your plot suggests there may be some other issue, because there is a very slow increase on the left but the right part is horizontal with a very sharp upper corner. Please post a minimum working example
Thanks all. So far `min` is the fastest. I have [tested](https://gist.github.com/magnesium2400/48b70aa3291e07f24e8cffffbf627bfc) on 1000*1000 sparse logical matrices but will actually end up using matrices up to 30k*30k.
Have you considered to check whether your shift works like intended by inspecting the spectrum before and after shifting ?
For loop inside While loop not breaking - Matlab
Please reread the tag descriptions that you picked. The tag [tag:STL] is not suitable to your question.
nice to know... but it sounds anyway pointless since I'm compiling a DLL not an exe
mfilename returns the path of the script. When you compile MATLAB code with MATLAB Compiler, it creates a CTF file, which is in essence just a ZIP file bundling all M-files and data files together. When this “executable” is run, this CTF file is unpacked into a temporary directory, the scripts are run from there. So this is the mfilename you see. In code bundled into a CTF file, you can use cftroot to get the directory where the CTF file is unpacked. This is the root for all the files while the program is running. There doesn’t seem to be a way to find the directory where the CTF itself is. Note that pwd shows the working directory, which can be set by the user when launching a program, and can be changed by the program. Do not depend on it to find the CTF file. It sounds like your are deploying the CTF file together with data files, and you want to locate these data files. Instead of putting those next to the CTF file, put them inside. You can use the -a option to the mcc command to include any file or directory into the CTF file, see here.
Wolfie (Bill's comment from proving ground), pt 1: v can be very small to very big, e.g. anywhere from 20 to 20000. m and n also have very wide ranges, either one can be between 400 to 200,000. Assuming max values for m and n are 200,000, that means L can be at most a 40 billion entry sparse matrix. Additionally, the larger these L matrices are, the fewer the percentage of entries in it that are nonzero (e.g. in the max case of 40 billion entries, I'd assume that less than 1e-5 % or the entries of L are nonzero (400,000).
thanks for your clarification. I assumed that referrring to the pointers would be sufficient, but agree, I could formulate more clear, with a simple code example.
Regarding difference between event and callback I suspect somehow like this is happening in matlab arcanes: Mouse is moved > HitTest cache is reset > Event `WindowMouseMotion` is fired > HitTest cache is updated > `WindowButtonMotionFcn` callback is called
Preamble Some time ago, I created an application in matlab where I could move/rotate some object directly from the mouse (i.e. some kind of mini-cadtool interface): I created the application on the go and was directly attaching to WindowButtonMotionFcn callback in figure properties and using the undocumented hittest function to detect objects below the mouse and everything was fine ... Now I would like to rework this code to extract cad-manipulation part to some sort of uicad object just like we can have uicontrol, uipanel, etc... so I can use it as component on the shelf and plug it in any figure I want. Especially I wanted not to directly modify WindowButtonMotionFcn of the parent figure ... Indeed, if I want to do something modular, I cannot guarantee that this callback is not already in use (or will be in use) by someone else. I then figured out that I could use equivalent WindowMouseMotion event in figure object so this way it is possible to attach as many event listeners as we want (see addlistener) without disturbing other listeners or even disturbing the WindowButtonMotionFcn property itself (which support only one listener). Problem Unfortunately when using event instead of callback (which obviously should be the same), hittest function no longer work as espected and no longer return the object which is below the mouse. Below code illustrate the issue: function [] = TestFigEvents() %[ % Create figure fig = figure(666); clf(fig, 'reset'); fig.Color = 'black'; % Add axes ax = axes(); daspect(ax, [1 1 1]); ax.Visible = 'off'; ax.Clipping = 'off'; view(ax, -45, 30); % Add something s = surface(ax, 160*membrane(1,100)); s.EdgeColor = 'none'; % Different way to attach to mouse move event if (true) fig.WindowButtonMotionFcn = @onMouseMove; else addlistener(fig, 'WindowMouseMotion', @onMouseMove); end %] end function [] = onMouseMove(s, e) %[ ht = hittest(s); % Will only detect correct object if using 'WindowButtonMotionFcn' disp(ht); %] end When going through WindowButtonMotionFcn, the hittest function indeed return the correct surface object when the mouse is over it. But when going through WindowMouseMotion event it is always returning the figure object only. Question Well I guess nobody outside Mathworks staff can help me solving for undocumented hittest not working when using events instead of callbacks, anyway: Is there another fast way I can detect objects below the mouse pointer rather than using hittest ? Is there a way I can attach to WindowButtonMotionFcn callback even if some callback is already defined for it ? Maybe there already exist some sort of uicad toolbox that I could use to move/rotate object easily from the mouse (paying toolbox is ok) ? edit I tested both with R2022b and R2024b ... and also both with figure and uifigure ... Here below is test code with uifigure: function [] = TestUiFigEvents() %[ % Create figure fig = uifigure(); fig.Color = 'black'; % Add axes ax = uiaxes(fig); daspect(ax, [1 1 1]); ax.Visible = 'off'; ax.Clipping = 'off'; view(ax, -45, 30); % Add something s = surface(ax, 160*membrane(1,100)); s.EdgeColor = 'none'; % Different way to attach to mouse move event if (false) fig.WindowButtonMotionFcn = @onMouseMove; else addlistener(fig, 'WindowMouseMotion', @onMouseMove); end %] end function [] = onMouseMove(s, e) %[ ht = hittest(e.Source); % Will only detect correct object if using 'WindowButtonMotionFcn' disp(ht); %] end
I also tried to specify the .net framework 4.8 in mcc line.. nothing changes.
When on remote desktop, for all my colleagues and myself, matlab creates a figure that is for half outside of the screen and we cant see it until you enlarge it. Is there a permanent fix that doesnt require changing updating all our hundreds matlab scripts? If not, what are the best lines of code to have this working in general (remotely or locally) It doesnt happen if we open it locally.
mfilename not predictable value return for compiled code
"matlab -nodesktop -nosplash -r `"run('model.m'); exit;`""
Appended a 3rd way to catch zeros with while loops, reducing x10 time required. x = sparse(5000,1); % Create sparse array [10% filled] x(randsample(5000,500)) = 1; nRuns = 1e5; idx = zeros(nRuns,1); % Find first element, a million times tag1=tic; for n=1:nRuns idx(n) = find(x==0,1); end t1=toc(tag1) %% % x = sparse(5000,1); % Create a sparse array [10% filled] % x(randsample(5000,500)) = 1; % nRuns = 1e5; idx = zeros(nRuns,1); % Find the first element, a million times tag2=tic; for n=1:nRuns for kk = 1:numel(x) [ii,jj] = ind2sub(size(x), kk); if x(ii,jj)==0; idx(n) = ii + (jj-1)*n; break; end end end t2=toc(tag2) %% tag3=tic; idx=[]; nx_max=prod(size(x)); nx=1; while nx&lt;nx_max while ~x(nx) nx=nx+1; idx=[idx nx]; if nx&gt;=nx_max break; end end nx=nx+1; end t3=toc(tag3) resulting : t1 = 0.563633000000000 t2 = 0.420241800000000 t3 = 0.017343400000000 To compare delays there's no need to generate a different sparse matrix x for each case, on the contrary, using the same matrix x one makes sure that the comparison is correct because it's on exactly the same matrix.
Wolfie (Bill's comment from proving ground), pt 2: "It will be hard to beat A * B. If you compute C = A * B you can index the values you seek with D = C(L) if L is logical, or D=C(logical(L)) if L is numeric containing 0s and 1s" I could not get D=C(L) to work for logical L as I received the error "Array indices must be positive integers or logical values." I think they mean D=C(find(L)) instead of D=(C(L)) which errors out. I tested and D=C(find(L)) is slower. (A * B) takes 18.8 sec, (A * B) .*L takes 28.5 sec, and D=C(find(L)) takes about 92 seconds.
I fixed the problem simply removing: CMDLINE250="mt -outputresource:$EXE';'2 -manifest $MANIFEST" I don't know why this option have been added to the command line (it's a reccomendation provided by MatLab support) but it deals with a manifest that's not available following the standard workflow for creating the library. Removing it just let the process and gracefully and the DLL file is finally created.
Because a `while` loop only checks its guard at the start of each iteration.
Sparse arrays store non-zero elements in order. Just look through those until you find a missing element.
How to create a CCS ToolchainInfo object in Matlab2023?
But I was thinking of looking through the data as stored: a sparse matrix stores indices to non-zero elements and their values. You should be able to iterate faster over just the indices of the non-zero elements. Except I don’t know how to get that data in MATLAB. In a MEX-file this would be simple: https://www.mathworks.com/help/matlab/apiref/mxgetir.html — indexing into a sparse array is more expensive than indexing into a full array.
I have two STL files of medical data. The Medical Registration Estimator app does not accept this format. How can I do registration of this two surfaces? Thanks! I tried using the registration estimator after saving the triplot images of the stl files. I tried ICP but the clouds are visualy not registered, far from each other: %Align Two Point Clouds Using Plane-to-Plane ICP Registration %reference reference_data = stlread('ref.stl'); reference_points = reference_data.Points; ptCloud = pointCloud(reference_points(:,:,:)); pcshow(ptCloud) %moving moving_data = stlread('moving.stl'); moving_data_points = moving_data.Points; moving_ptCloud = pointCloud(moving_data_points(:,:,:)); pcshow(moving_ptCloud) %Register two point clouds tform = pcregistericp(moving_ptCloud,reference_ptCloud); figure pcshowpair(moving_ptCloud,reference_ptCloud,VerticalAxis="Y",VerticalAxisDir="Down")` How can I improve it? Thanks!
The C++ standard library has the Mersenne Twister algorithm. But there are two things you need to replicate from `rand`: the random number generator (which generates integers), and the conversion to the 0-1 range. This last step has multiple possible implementations as well, you’ll have to figure out how MATLAB does it.
R & MATLAB integration in Windows 10
So you are trying to generate an array that has the values described by the histogram? That is curious, what do you need it for? Note that your output might have more zeros than described by the histogram.
@chtz If `A` and `B` can be reordered so that the result can be obtained with (sub-)matrix multiplication, I think that can save time and is worth a separate answer. I fail to see how to do that
One can easily concatenate (stack up) four arrays by using: B = cat(3, A, A, A, A); % here A is 2-dimensional M x N matrix and B is 3-dimensional M x N x 4 stack How is it possible to concatenate (stack) n arrays to get M x N x ... x n array? The dimenisonality of A array is known (or easy to figure as numel(size(A))) B = A; % A is M x N 2-dimensional array here for ii = 1 : n-1 B = cat(3, B, A); end is very poor, B = nan([size(A),n]); for ii = 1 : n B(:, :, ii) = A; end is quite slow too. The motivation is to find the array in S-stack that is closest to the array A. If I want to find element of vector S closest to a scalar a it is super simple: distances = abs(S - a); FOO = find(distances == min(distances),1); but this opperation S - a works only for arrays of same size or when a is a scalar. In more general manner I want to perform a dot-opperation on B and A, like B.*A, B./A, etc.
I have created a shallow fully connected NN that has an input layer, 1 hidden layer and an output layer. I want to set some of the weights of the hidden layer with specific values and freeze them so that the values don't change during training. I have noticed that in MATLAB it is possible to freeze a particular layer but I don't see any solutions that are related to specific weights. Can someone guide me on how to get started with it? Thanks!
After that if you think that the performance isn't satisfying you can implementing a parallel version of `repelem` in a c/c++ mex function that.
to magnesium, chtz, and Louis, pt 2: I indeed found it faster: for the dimensions of the data I used, (A * B) too 18.8 sec, (A * B) .* L took 28.5 sec, and my "blocklooping" solution above took about 7.0 sec. But I should also note, in the thread on reddit (https://www.reddit.com/r/matlab/comments/1iro2m4/need_to_vectorize_efficiently_calculating_only/mdfs8l3/?context=3), a user "86billionfireflies" provided a vectorized solution that was faster than my "blocklooping" solution: 86's solution took 5.4 sec.
Use `break` or `return` to exit the `for` loop early.
The values in the 1st column are not deleted, there just are not enough decimal places to print both `-1.3275e-17` and `-0.2168`, so the first column just shows `-0.0000`. If you display `A(1,1)`, you'll see that the correct value is still there.
Performance Issues with EIGEN vs Matlab with elementwise operations
What is `load_nav_data()`? Did you check that it produces the same output in both versions? It is likely that the two MATLABs have different files on their paths, and thus both could be running a different version of some function you depend on. MATLAB itself is unlikely to have changes that cause something to work in one version and not another. If you depended on new functionality not yet present in your 2022 version, you should be getting an error in that version.
Note that `tic/toc` is not recommended for accurate timings for a multitude of reasons. Use [`timeit()`](https://www.mathworks.com/help/matlab/ref/timeit.html) instead. This circumvents several problems, mainly the start-up time of the engine and averaging out differences in run time between runs.
Please provide a title that actually summarizes your question or problem.
I'm having trouble understanding what Matlab does regarding the lsim function. As far as I know, if I give Matlab a continuous-time transfer function and a sampled input and vector time, I normally discretizes the transfer function by using a zero-order hold or a first-order hold (ZOH or FOH). However, when I try to compare directly using lsim, and using lsim on both discretized models, I don't get matching results, neither for y_zoh or y_foh (none of them are identical to y_cont). I used this small code to try to understand the function better: Ts=0.1; %sampling time t=0:Ts:10; %time vector u=cos(t); %input signal G=tf(1,[1 1]); %Continuous-time model y_cont=lsim(G,u,t); %Output of the continuous-time model Gzoh=c2d(G,Ts,'zoh');%ZOH discretization y_zoh=lsim(Gzoh,u); Gfoh=c2d(G,Ts,'foh');%FOH discretization y_foh=lsim(Gfoh,u,t); Question: Could somebody explain what is Matlab doing differently regarding the computation of y_cont with respect to y_foh (as the input is a cosine, normally Matlab should use a FOH)?
Thank you, Rahnema1! I've tried your solution and it is ~2X faster at the cost of 25GB memory on my dataset. It is very clever and insightful. I'm just thinking is there a better way of doing this conversion? Because from my rough understanding it is nothing more than a lot of copies of values, is it? I've also edited my question and provide my data as well as your solution. Thank you again for your insights and help!
Sorry Luis I was not specific, I only need to compute the nonzero entries of C as a vector.
I dont want to be the arse, but you are quoting directly from their homepage. Without proper attribution this is a form of plagiarism. Why not add a link to the question? I will do that for you....
Extracting Vessel Dimensions from 2D Fluorescence Microscopy Images in MATLAB
i.e. the naive loop I have above (in the second part of the snippet) -- or do you mean something else? Is that really the fastest way?
TypeInitia​lizationEx​ception, BadImageFormatException using a .net assembly created in MatLab 2019b 64bit
Good afternoon. I want to write a code to output experimental frequency response for system identification. For verification I use the modeled sinusoid and the response of the modeled system. To exclude the influence of transient process and in the future measurement noise, I want to determine the amplitude and phase of the system output using Fourier analysis. The amplitude is fine, but the phase is a problem. I tried my own code and the code from Matlab doc. I decided on the code from the video: https://www.youtube.com/watch?v=ZvYGqYOyesk. I still have a problem with the phase. I watch amplitude and phase at the input frequency respectively. I compared with the results of lsqcurvefit. My code: close all, clear, clc; step_t = 0.01; T = 5; w = (2*pi)/T; Am = 2; t_real = 0:step_t:100; sin_mass = Am*sin(w*t_real); Tf = 10; sys = tf([0 1],[Tf 1]) y = lsim(sys,sin_mass,t_real); figure() plot(t_real, sin_mass, t_real, y),grid on legend('input','output') [f,F_x_f]=fourier(t_real,y,'sinus'); % plot the magnitude spectrum figure(2) stem(f,abs(F_x_f)) grid on xlim([0,20]) xlabel('Frequency in Hz') ylabel('Amplitude spectrum of the force in N') % plot the phase spectrum figure(3) stem(f,angle(F_x_f)) grid on xlim([0,20]) xlabel('Frequency in Hz') ylabel('Phase spectrum of the force in °') [M,I] = min(abs(f-(1/T))); out_prob = F_x_f(I); Amplitude_est = abs(out_prob) Phase_est = angle(out_prob) f_out = @(x,u)x(1)*sin(w*u + x(2)); par0 = [Am,0]; par_out = lsqcurvefit(f_out, par0, t_real, y') y_est = par_out(1)*sin(w*t_real + par_out(2)); figure() plot(t_real, y, t_real, y_est),grid on legend('output','output est') Function fourier from the video: function [f,X_f]=fourier(t,x_t,modus) % check if mode is set if nargin&lt;3 % set to default value modus='pulse'; end % Number of values -&gt; scalar N=length(t); % maximum time (in s) -&gt; scalar t_max=t(N); % Time step (in s) -&gt; scalar t_step=t(2); % maximum frequency (in Hz) -&gt; scalar f_max=0.5/t_step; % perform Fourier transform -&gt; vector of length N if strcmp(modus,'pulse') % the unit of the spectrum is 1/Hz (e.g. V/Hz, A/Hz, ...) XX(1:N)=t_max/(N-1)*fft(x_t); elseif strcmp(modus,'sinus') % the unit of the spectrum is 1 (e.g. V, A, ...) XX(1:N)=2/N*fft(x_t); else error(['The modus ',modus,' is unknown.']) end % Meaning: % for even N: % XX(1) contains the DC component (real) % XX(2:N/2) contains the positive frequency components in ascending order (usually complex) % XX(N/2+1) contains the highest frequency (real) % XX(N/2+2:end) contains the negative frequency components in decreasing order (usually complex) % for odd N: % XX(1) contains the DC component (real) % XX(2:(N+1)/2) contains the positive frequency components in ascending order (usually complex) % XX((N+3)/2:end) contains the negative frequency components in decreasing order (usually complex) % check whether N is even or odd if mod(N,2) % N is odd % create frequency spectrum -&gt; row vector X_f(1:(N+1)/2)=XX(1:(N+1)/2); % create frequency range (in Hz) -&gt; row vector f=linspace(0,f_max*(N-1)/N,(N+1)/2); else % N is even % create frequency spectrum -&gt; row vector X_f(1:N/2+1)=XX(1:N/2+1); % create frequency range (in Hz) -&gt; row vector f=linspace(0,f_max,N/2+1); end end
how to get a transparent background in Matlab for wordcloud
I am a student studying MATLAB. I am working on creating a code for convolution without using the conv2 function. To perform the convolution, I first need to create a grayscale image, but I am encountering an issue. The grayscale image created using the rgb2gray function and the grayscale image created using my custom code have slightly different values. I believe this is due to floating-point issues, where the rounding doesn't work properly, and the values differ. Rounding does not work correctly for values with a decimal of 0.5. Even though I added code to manually round the values, the problem persists. How can I make sure that the difference between the two images (the grayresult value) becomes 0? Could you please help me with this? enter code here clc; clear; close all; image = imread("KakaoTalk_20250321_165344568.png"); % --------------grayscale applied using a function----------------------- grayfun = rgb2gray(image); % ----------------Grayscale without a function-------------------------- for i = 1:size(image,1) for j = 1:size(image,2) R(i,j) = image(i,j,1); G(i,j) = image(i,j,2); B(i,j) = image(i,j,3); end end R = double(R); G = double(G); B = double(B); % gray = R*0.2989 + G*0.5870 + B*0.1140; gray = R*0.298926034245627 + G*0.587034707055387 + B*0.114039258699985; gray2 = gray ##-----------------Manually rounding------------------------------------ for i = 1:size(image,1) for j = 1:size(image,2) decimal_part = gray(i, j) - floor(gray(i, j)); first_decimal = floor(decimal_part * 10); if first_decimal >= 5 grayman(i, j) = ceil(gray(i, j)); else grayman(i, j) = floor(gray(i, j)); end end end %----------------------------------------------------------------------- grayman = uint8(gray); %---------------Subtraction calculation----------------------------------- graysubresult = sum(sum(abs(grayfun) - abs(grayman))); grayresult = abs(grayfun) - abs(grayman);
How to perform OLS regression in Matlab with constraints on coefficients?
For a start, is this Octave code rather than MATLAB code? `endif` is not valid MATLAB syntax, it would be best if you tagged your question for the specific language you're using to get answers you can definitely use.
I have tried to do this using a C caller block and then using C++ vectors, but the error that arises suggests C caller blocks do not support C++. Is this correct? Next I tried to use a Matlab Function block, with which I attempt to call code in my C file. However, it seems to object to calling a C function of multiple inputs with a coder.ceval statement and I'm just wondering if this is actually possible? If so, what should the syntax be? I am doing this for someone else on their pc and do not have it on my pc, so can't see it right now, but as I recall, my effort was something like this: function [a,b,c,d] = callingCcode (x,y) x = coder.ceval('Ccode',(x,y)) It seems to object to the multiple inputs in the coder.ceval line, as I say. Having just taken a look at coder.ceval, I see it can only return a single scalar output. I want it to return more than one double as an output, so I'm just wondering if it's not possible this way and if so, whether there's any other way to do this? What I'm seeking to do again is to have a block with multiple inputs and outputs which calls C Code.
It could be done other way around You could take IT++ random module and convert it to MEX function, callable from MATLAB
MATLAB transform XML file into pointcloud
Mathworks did not add some basic features as single cell run in visual studio code. You can run all the code or run selection. But there is no way to run current cell. The cells are divided by %%. Is there a way to select all the code between %% to then run selection? Select to bracket can only select the code between default brackets ()[]{}, but not %%. Is there a way to run or just select the cell? matlab cell
In matlab, the function fitcsvm trains a support vector machine. In output, there is a component BoxConstraints. I have read the post this post and understood the meaning of box constraint. But in the answer of the post, the box constraint C is a scalar, while in the output of Matlab it is a vector with same length of number of samples, and it is all 1, where I have used default box constraint 1 in the input. I do not understand what is the output. (I have read the sections of SVM on the Element of Statistical Learning, and did not find this term. So I think perhaps it is different choice of term. If you would like to answer, you could skip explaining basic concepts of SVM.)
With the following 2 support functions 1.- function [a b c d]=plane_points_to_coeffs(A,B,C) % input : 3 plane points % output : [a b c d] plane coefficients % no check whether 3 points may be parallel x1=A(1);y1=A(2);z1=A(3); x2=B(1);y2=B(2);z2=B(3); x3=C(1);y3=B(2);z3=C(3); a=(y2-y1)*(z3-z1)-(z2-z1)*(y3-y1); b=(z2-z1)*(x3-x1)-(x2-x1)*(z3-z1); c=(x2-x1)*(y3-y1)-(y2-y1)*(x3-x1); d=-(a*x1+b*y1+c*z1); 2.- function L=dist_point_plane(P,a,b,c,d) % input point P = [x y z] % input plane coefficients [a b c d] % L : output distance point to plane L=abs(a*P(1)+b*P(2)+c*P(3)-d)/(a^2+b^2+c^2)^.5; and script % 1st object A1 = [-50.0098 -181.0869 -37.5881]; B1 = [-49.8410 -180.8097 -41.1383]; C1 = [-49.5887 -180.3952 -46.4462]; % 2nd object A2 = [-50.199 -180.93 -37.249]; B2 = [-50.256 -180.823 -33.686]; C2 = [-50.341 -180.657 -28.359]; % 1st plane [a1 b1 c1 d1]=plane_points_to_coeffs(A1,B1,C1); % 2nd plane [a2 b2 c2 d2]=plane_points_to_coeffs(A2,B2,C2); % distances 1st plane to points on 2nd object L_plane1_A2=dist_point_plane(A2,a1,b1,c1,d1) L_plane1_B2=dist_point_plane(B2,a1,b1,c1,d1) L_plane1_C2=dist_point_plane(C2,a1,b1,c1,d1) % distance2 2nd plane to points on 1st object L_plane2_A1=dist_point_plane(A1,a2,b2,c2,d2) L_plane2_B1=dist_point_plane(B1,a2,b2,c2,d2) L_plane2_C1=dist_point_plane(C1,a2,b2,c2,d2) I obtain L_plane1_A2 = 1.035855768604593e+02 L_plane1_B2 = 1.034733625214198e+02 L_plane1_C2 = 1.033053734283317e+02 L_plane2_A1 = 1.018878096607852e+02 L_plane2_B1 = 1.017752913940908e+02 L_plane2_C1 = 1.016071380599225e+02 I have corrected the error kindly pointed by Jonathan in plane_points_to_coeff Now, I got the distance(point,plane) formula from https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_plane In this source d has a negative sign. I'd like to agree with Jonathan again upon another error here, that -d should be +d because it makes more sense to calculate with ax+by+cy+d but I am going to keep both in this my answer, for the question originator to find out whether the formula in Wikipedia is the source of the error, or there's a 30dB distance error and d should remain -d . With +d the results agree with Jonathan's L_plane1_A2 = 0.172913873214268 L_plane1_B2 = 0.060699534174707 L_plane1_C2 = 0.107289558913367 L_plane2_A1 = 0.183549819138508 L_plane2_B1 = 0.296068085832844 L_plane2_C1 = 0.464221420001122
@jdweng: It is only _PowerShell_ that uses `\`` as the escape character, and PowerShell is _not_ in the picture when R's `system()` function is called, so your suggestion cannot possibly help. MATLAB's `-r` option does _not_ create a report file, and per [the docs](https://www.mathworks.com/help/matlab/ref/matlabwindows.html) you need either `-r` or `-batch` to execute statements, so your advice is misleading. Please only comment if you understand the question and hand and have subject-matter expertise or you can at least point to documentation to back up your claims.
Trying to solve the signal subtraction analytically for s1-s2=0, exp(-1j*8*pi/lambda*(V^2*ta*time_delay)/R) = 1 ; Base on the parameters that are fixed, it might be easier for you to solve this equation. PS: This is my first answer so forgive me if it is too crude.
Octave contour function returns an unaccpected erro message
g++ version 12.2.0 optimizes the outer loop away with flags `-Ofast -mavx2 -mfma`. What compiler flags did you use?
A lot is unclear here. Please [edit] the question to clarify. what is IT++ ? Why is this tagged `signal-processing` and `communication` ?
Pass parameters to exe-file (compiled from Simulink)
yes I agree with you magnesium, the Luis and fireflies codes appear to be nearly the same, its very puzzling how different their times are recorded. Perhaps fireflies solution may be avoiding additional overhead with indexing by not defining C as a sparse matrix and then by calculating all of C directly instead of indexing in C. That has its own problems, then Luis' solution would be much more memory friendly.
In addition to removing `ind2db` as Cris said, replacing `x(kk)==0` by `~x(kk)` may help a little
Read up on `?system2` and rework your `system` line to use that instead.
I have edited the answer. contourf creates filled contours, and contourcmap can modify color
`set(gcf,"Position",[200,200,200,200])`, where gcf gets the figure handle, the 4 element vector is (L to R) [X, Y, width, height] on screen. This could be done inside a program or in the command window at any time.
Your defining of `R`, `L`, `C`, and `V0` as double values wipes the previously defined symbolic variables of the same names. Just `syms i(t)` is needed in your first line.
Which version of MATLAB are you using? Answers concerning the latest JavaScript-based uifigure interaction might be very different to what came before
I have dowloaded a MATLAB file with species names and their ecological group from https://ambi.azti.es/download/ In step 5 on this page the file library.mat can be downloaded (zipped). I then use the function readMat() from the R.matlab library to read this file: library(R.matlab) ambi<-readMat("library.mat") I get this 7 warnings: Warning messages: 1: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw 2: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw 3: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw 4: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw 5: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw 6: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw 7: In convertUTF8(ary) : out-of-range values treated as 0 in coercion to raw I don't know what this means but I suspect it has something to do with encodings. I would be very thankful if someone can tell me what the reason is and how I can solve this problem. I don't have MATLAB. I am using R version 4.4.3 on Swedish Windows 11.
How can I copy & past a curve in yyaxis right to other plot for comparison in Matlab plot?
I found the code ran much faster after I had preallocated the variable `a`. Thanks for your help!
STL files are 3D geometry, so that's not exactly "image processing". you need something like Iterative Closest Point (ICP) for alignment of point clouds. I'm sure a variant of that exists for meshes too, or some other algorithm, anyway that's the class of problem you have here. -- if you had *voxel data* instead (as a source), that too can be aligned, without conversion, with other approaches. whatever source data you have is alignable. we just need to know what type of data it is, originally, for best advice.
That is correct. For non-scalar outputs you use coder.wref or coder.ref and pass them as inputs to coder.ceval. You need to initialize those variables before passing them to coder.ceval.
I am trying to draw a decision boundary for fisherisis dataset on Matlab. Below is the code that I am working on: load fisheriris; X = meas(:,1:2); y = species; % PLOT figure; plot(X(strcmp(y,"setosa"),1),X(strcmp(y,"setosa"),2),'.','DisplayName','setosa'); hold on plot(X(strcmp(y,"versicolor"),1),X(strcmp(y,"versicolor"),2),'.','DisplayName','versicolor'); plot(X(strcmp(y,"virginica"),1),X(strcmp(y,"virginica"),2),'.','DisplayName','virginica'); hold off legend("setosa","versicolor","virginica") % SVM t = templateSVM("KernelFunction","polynomial", "BoxConstraint",1,"KernelScale","auto","PolynomialOrder",2,"Standardize",1); SVMModel = fitcecoc(X,y,"Learners", t); % DECISION BOUNDARY %%% Draw decision boundary here The above SVMModel I am using is classified multiclass SVM (3 classes: "setosa", "versicolor", "virginica") and 2 first column of the dataset for the train data. I am expecting that I can plot 2 or 3 lines or curves displaying the boundary of each species in my SVMModel. I have read several websites that somewhat included my problems but nothing works for me because they are using linear SVM or they are using linear equation... Below is list of websites that I have searched about: First website, but this is for binary classification, in my case, I have 3 classes. Second website, but this is for linear SVM, in my case is polynomial kernel function. Third website, but in this situation, the properties of ecoc has the property Beta, in my case the Beta is not provided. Anyone have any idea how to draw decision boundary in my situation? Thanks a lot in advance.
try [dsp.se] or [electronics.se]. this doesn't look like an actual programming problem, but a math problem.
Please solve the issue with the grayscale image
How to freeze certain weights of hidden layer neurons during training in a feedforward network in MATLAB?